0

I have seen a lot of posts on this topic with all solutions being based on Java and not Kotlin. Is there a solution similiar to the one using Java but in Kotlin?

1 Answers1

0

first get a screenshot of the layout:

getViewScreenshot(view: View): Bitmap {
    view.setDrawingCacheEnabled(true)
    val bitmap = Bitmap.createBitmap(view.getDrawingCache())
    view.setDrawingCacheEnabled(false)
    return bitmap
}

then blur it with this function:

fun blurBitmap(bitmap: Bitmap, applicationContext: Context): Bitmap {
    lateinit var rsContext: RenderScript
    try {

        // Create the output bitmap
        val output = Bitmap.createBitmap(
                bitmap.width, bitmap.height, bitmap.config)

        // Blur the image
        rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.DEBUG)
        val inAlloc = Allocation.createFromBitmap(rsContext, bitmap)
        val outAlloc = Allocation.createTyped(rsContext, inAlloc.type)
        val theIntrinsic = ScriptIntrinsicBlur.create(rsContext, Element.U8_4(rsContext))
        theIntrinsic.apply {
            setRadius(10f)
            theIntrinsic.setInput(inAlloc)
            theIntrinsic.forEach(outAlloc)
        }
        outAlloc.copyTo(output)

        return output
    } finally {
        rsContext.finish()
    }
}
Hamid Sj
  • 983
  • 7
  • 19
  • @Sumsidum Your welcome, but please accept my answer or use upvote to thank me =) – Hamid Sj Feb 18 '21 at 21:49
  • Thanks for the answer! Still got a problem. When I pass in the LinearLayout on the getViewScreenshot(), I get the Error that the bitmap.getWidth is null (I imagine the bitmap.getHeight will be null too). Do you have a guess why this happens and how to fix it? The LinearLayout I pass in from the activity_main.xml definitily has a height and a width My code: LinearLayout I pass in: `var bitmap = getViewScreenshot(bluredGlass)` Error I get on that line: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference – Maximilian Dietel Feb 18 '21 at 21:55
  • Yeah... Im new so I didnt knew that the Enter key adds the comment and not opens a new line... Im sorry for that. Still accept your answer as this is 95% the code I was searching for, just need to get that error fixed. – Maximilian Dietel Feb 18 '21 at 22:01