How do you extract the underlying Bitmap from an ImageView with RenderEffect?

378 views Asked by At

I've been looking into applying blur to a Bitmap via ImageView using RenderEffect. I'm able to do so through setRenderEffect. However, when I try to get Bitmap out of the ImageView,  using the below (hacky) code, it does not have the blur applied to it. I believe this is because the layer is applied but not to the underlying bitmap in the ImageView (not 100% certain). This leads me to the question of: how do you get the underlying Bitmap associated with an ImageView that is rendered on the screen after RenderEffect has been applied?

        val testImageView = ImageView(applicationContext)
        testImageView.setImageBitmap(someBitmap)
        val blurEffect = RenderEffect.createBlurEffect(30.0f, 30.0f, Shader.TileMode.MIRROR)
        testImageView.setRenderEffect(blurEffect)
        testImageView.invalidate()
        val testDrawable = testImageView.drawable as BitmapDrawable
        val testBitmap = testDrawable.getBitmap(); // This doesn't have Blur applied to it even though I'd like it to.

Using RenderScript looks possible but it's been deprecated past API 31, so I've been looking for an alternative.

1

There are 1 answers

0
Alex Reye On

As render effects are applied only on drawing, you need to draw your entire ImageView to Canvas to see the blurred result. The next code might be helpful:

fun getBitmapWithBlur(imageView: ImageView): Bitmap {
    val bitmapWithBlur = Bitmap.createBitmap(imageView.width, imageView.height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmapWithBlur)
    imageView.draw(canvas)
    return bitmapWithBlur
}