Dans l'API Android, 28 view.getDrawingCache()
est obsolète. Existe-t-il une nouvelle solution pour générer une image bitmap d’une vue particulière dans Android?.
J'ai trouvé un moyen d'utiliser l'API PixelCopy pour récupérer la vue sous forme de bitmap. Kotlin d'occasion
fun getBitmapFromView(view: View, activity: Activity, callback: (Bitmap) -> Unit) {
activity.window?.let { window ->
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val locationOfViewInWindow = IntArray(2)
view.getLocationInWindow(locationOfViewInWindow)
try {
PixelCopy.request(window, Rect(locationOfViewInWindow[0], locationOfViewInWindow[1], locationOfViewInWindow[0] + view.width, locationOfViewInWindow[1] + view.height), bitmap, { copyResult ->
if (copyResult == PixelCopy.SUCCESS) {
callback(bitmap)
}
// possible to handle other result codes ...
}, Handler())
} catch (e: IllegalArgumentException) {
// PixelCopy may throw IllegalArgumentException, make sure to handle it
e.printStackTrace()
}
}
}
Canvas Example
RelativeLayout view = (RelativeLayout)findViewById(R.id.relativelayout);
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null) {
bgDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);
PixelCopy Api
https://stackoverflow.com/a/52985554/9909365
Pour plus
https://developer.Android.com/reference/Android/graphics/Bitmap
https://developer.Android.com/reference/Android/graphics/Canvas
En tant que documentation officielle getDrawingCache () , vous devez utiliser l’application PixelCopy .