繁体   English   中英

如何从Android的根视图中删除模糊

[英]How to remove the blur from root view in android

我正在使用此类在活动中模糊根视图的背景:

object BlurBuilder {
private val BITMAP_SCALE = 0.4f
private val BLUR_RADIUS = 20f


fun blur(v: View): Bitmap {

    return calculateBlur(v.context, getScreenshot(v))
}


fun calculateBlur(ctx: Context, image: Bitmap): Bitmap {
    val width = Math.round(image.width * BITMAP_SCALE)
    val height = Math.round(image.height * BITMAP_SCALE)

    val inputBitmap = Bitmap.createScaledBitmap(image, width, height, false)
    val outputBitmap = Bitmap.createBitmap(inputBitmap)

    val rs = RenderScript.create(ctx)
    val theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))
    val tmpIn = Allocation.createFromBitmap(rs, inputBitmap)
    val tmpOut = Allocation.createFromBitmap(rs, outputBitmap)
    theIntrinsic.setRadius(BLUR_RADIUS)
    theIntrinsic.setInput(tmpIn)
    theIntrinsic.forEach(tmpOut)
    tmpOut.copyTo(outputBitmap)

    return outputBitmap
}


fun getScreenshot(v: View): Bitmap {
    val b = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
    val c = Canvas(b)
    v.draw(c)
    return b
    }
  }

在我的活动中,我有以下几点:

 fun applyBlur() {
    val view = this.findViewById(android.R.id.content).rootView

    if (view.width > 0) {
        val image = BlurBuilder.blur(view)

        window.setBackgroundDrawable(BitmapDrawable(this.resources, image))
    } else {
        view.viewTreeObserver.addOnGlobalLayoutListener({
            val image = BlurBuilder.blur(view)
            window.setBackgroundDrawable(BitmapDrawable(this.resources, image))
        })
    }
}

通过这种技术,我可以根据模糊半径来模糊活动的根视图。 我该如何做相反的事情? 我试图将BLUR_RADIUS设置为0.1f,但仍然无法正常工作。

请提供一些有关如何实现此目的的说明。 谢谢!

模糊是一种破坏性的操作,要逆转它需要一些复杂的数学运算和计算,您最好添加一个标志,并在模糊函数中对其进行检查(例如,如果标志为假),则只需传递原始背景即可,例如:

var contentBG: Drawable? = null
var needBlur = true
fun applyBlur() {
    val view = this.findViewById(android.R.id.content).rootView

    if (view.width > 0) {
        contentBG ?: let { contentBG = view.background }
        val drawable = if (needBlur)
            BitmapDrawable(this.resources, BlurBuilder.blur(view))
        else contentBG
        window.setBackgroundDrawable(drawable)
    } else {
        view.viewTreeObserver.addOnGlobalLayoutListener({
            val image = BlurBuilder.blur(view)
            window.setBackgroundDrawable(BitmapDrawable(this.resources, image))
        })
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM