2017-06-24 20 views
0

根視圖模糊我使用這個類來模糊在我的活動根視圖的背景:如何從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,但它仍然不起作用。

請提供一些關於如何實現此目的的解釋。謝謝!

回答

1

模糊是一種破壞性的操作,它需要一些複雜的數學和計算,你最好添加一個標誌,並在模糊函數中檢查它,如果標誌是假的,例如 - 只是傳遞原始背景通過,如:

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)) 
     }) 
    } 
} 
+0

我試過你的想法,但不幸的是我的根視圖背景變成黑色。爲什麼會發生? –

+0

@GabrielKuka你實際上使用這個解決方案或類似的東西? – Pavlus

+0

是的。我嘗試過這個。當我對圖像模糊不清時,我將isBlurNeeded設置爲false,以免它再次模糊。但是當我想把它取下時,它會消除模糊,背景變黑。 –