it-swarm.com.de

view.getDrawingCache () ist in der Android-API 28 veraltet

In der Android-API 28 wurde view.getDrawingCache() nicht mehr unterstützt. Gibt es eine neuere Lösung zum Erstellen einer Bitmap einer bestimmten Ansicht in Android?.

Ich habe einen Weg gefunden, die PixelCopy-API zum Abrufen der Ansicht als Bitmap zu verwenden. Gebraucht Kotlin

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()
        }
    }
}
  1. Canvas verwenden
  2. Pixel-API

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

Für mehr

https://developer.Android.com/reference/Android/graphics/Bitmap

https://developer.Android.com/reference/Android/graphics/Canvas

5
Ashvin solanki

Ab der offiziellen Dokumentation getDrawingCache () sollten Sie die PixelCopy api verwenden.

1
Antonio Vlasic

viel genauer Code ..

private fun convertViewToDrawable(view: View): Bitmap {
        val b = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight,
            Bitmap.Config.ARGB_8888)
        val c = Canvas(b)
        c.translate((-view.scrollX).toFloat(), (-view.scrollY).toFloat())
        view.draw(c)
        return b
    }
0
Asad

Versuche dies:

    private fun convertViewToDrawable(view: View): Bitmap {
    val spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    view.measure(spec, spec)
    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
    val b = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight,
            Bitmap.Config.ARGB_8888)
    val c = Canvas(b)
    c.translate((-view.scrollX).toFloat(), (-view.scrollY).toFloat())
    view.draw(c)
    return b
}
0
Shyam Kumar