高斯模糊類
public class FastBlur {
// 圖片縮放比例(即模糊度)
private static final float BITMAP_SCALE = 0.4f;
/**
* @param context 上下文對象
* @param image 需要模糊的圖片
* @return 模糊處理后的Bitmap
*/
public static Bitmap blurBitmap(Context context, Bitmap image, float blurRadius) {
// 計算圖片縮小后的長寬
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
// 將縮小后的圖片做為預渲染的圖片
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
// 創(chuàng)建一張渲染后的輸出圖片
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
// 創(chuàng)建RenderScript內(nèi)核對象
RenderScript rs = RenderScript.create(context);
// 創(chuàng)建一個模糊效果的RenderScript的工具對象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并沒有使用VM來分配內(nèi)存,所以需要使用Allocation類來創(chuàng)建和分配內(nèi)存空間
// 創(chuàng)建Allocation對象的時候其實內(nèi)存是空的,需要使用copyTo()將數(shù)據(jù)填充進去
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
// 設置渲染的模糊程度, 25f是最大模糊度
blurScript.setRadius(blurRadius);
// 設置blurScript對象的輸入內(nèi)存
blurScript.setInput(tmpIn);
// 將輸出數(shù)據(jù)保存到輸出內(nèi)存中
blurScript.forEach(tmpOut);
// 將數(shù)據(jù)填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}
引用
implementation 'com.github.xuexiangjys:XUI:1.0.9'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'com.google.android.material:material:1.1.0-beta01'
implementation 'com.github.bumptech.glide:glide:4.8.0'
使用代碼
ConstraintLayout background = findViewById(R.id.root_view);
View view = this.getWindow().getDecorView();//獲取當前視圖
Bitmap mBitmap = DrawableUtils.createBitmapFromView(view);//截取當前視圖為Bitmap
if (mBitmap != null) {
//blurRadius:模糊度
Bitmap overlay = FastBlur.blurBitmap(this, mBitmap, 25f);
BitmapDrawable drawable = new BitmapDrawable(this.getResources(), overlay);
background.setBackground(drawable);
} else {
//如果mBitmap為空宫屠,設置為預先準備圖片或顏色
background.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者