注意:ScriptIntrinsicBlur的相关方法只支持API 17及以上版本的系统,为了兼容旧版本,Google 提供了android.support.v8.renderscript
兼容包。android.support.v8.renderscript
兼容包的使用不需要在app/build.gradle
文件中额外添加依赖,而是在defaultConfig
配置中添加如下两行代码:
defaultConfig {
......
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
模糊方法:
public Bitmap blurBitmap(Bitmap bitmap){
//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(), Config.ARGB_8888);
//Instantiate a new Renderscript
RenderScript rs = RenderScript.create(getApplicationContext());
//Create an Intrinsic Blur Script using the Renderscript
ScriptIntrinsicBlur 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: 0 < radius <= 25
blurScript.setRadius(25.0f);
//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;
}