Android: 使用 Kotlin 模糊 LinearLayout 的背景

Android: Blur background of LinearLayout using Kotlin

我看过很多关于这个主题的帖子,所有解决方案都基于 Java 而不是 Kotlin。是否有类似于使用 Java 但在 Kotlin 中的解决方案?

首先获取布局截图:

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

然后用这个函数模糊它:

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()
    }
}