您可以尝试使用 RenderScript 来模糊图像的 Bitmap:
public Bitmap blurBitmap(Bitmap bitmap,Context context){
//Let's create an empty bitmap with the same size of the bitmap we want to blur
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//Instantiate a new Renderscript
RenderScript rs = RenderScript.create(context);
//Create an Intrinsic Blur Script using the Renderscript
ScriptIntrinsicBlur blurScript = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
//Create the Allocations (in/out) with the Renderscript and the in/out bitmaps
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
//Set the radius of the blur
blurScript.setRadius(25.f);
//Perform the Renderscript
blurScript.setInput(allIn);
blurScript.forEach(allOut);
//Copy the final bitmap created by the out Allocation to the outBitmap
allOut.copyTo(outBitmap);
}
//recycle the original bitmap
bitmap.recycle();
//After finishing everything, we destroy the Renderscript.
rs.destroy();
return outBitmap;
}
public Bitmap drawableToBitmap(Drawable drawable) {
int width = drawable.getIntrinsicWidth();
int heigh = drawable.getIntrinsicHeight();
drawable.setBounds(0, 0, width, heigh);
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(width, heigh, config);
Canvas canvas = new Canvas(bitmap);
drawable.draw(canvas);
return bitmap;
}
public void blurImage(View imageView, Context context){
Drawable drawable = imageView.getBackground();
Bitmap bitmap = drawableToBitmap(drawable);
Bitmap out = blurBitmap(bitmap,context);
BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(),
out);
imageView.setBackground(bitmapDrawable);
}
将它与视图 id 一起使用是 Activity 中的视图:
View view = findViewById(R.id.view);
blurImage(view,this);