工具类代码:
BlurBitmap
package com.example.administrator.myapplication;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
/**
* Created by yj on 2016/8/3.
*/
public class BlurBitmap {
/**
* 图片缩放比例
*/
private static final float BITMAP_SCALE = 0.4F;
/**
* 最大模糊度(0.0到25.0之间)
*/
private static final float BLUR_RADIUS = 25F;
/**
* 针对操作系统4.0以上的手机
*
* 模糊的具体方法
*
* @param context 上下文对象
* @param image 需要模糊的图片
* @return 模糊处理后的照片
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static Bitmap blur(Context context, Bitmap image) {
// 计算图片缩小后的长宽
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
// 将缩小后的图片做为预渲染的图片
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
// 创建一张渲染后的输出图片
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
// 创建RenderScript内核对象
RenderScript rs = RenderScript.create(context);
// 创建一个模糊效果的RenderScript的工具对象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并没有使用VM来分配内容
// 所以需要使用Allocation类来创建和分配内存空间
// 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
// 设置渲染的模糊程度, 25f是最大的模糊度
blurScript.setRadius(BLUR_RADIUS);
// 设置blurScript对象的输入内存
blurScript.setInput(tmpIn);
// 将输出数据保存到输出内存中
blurScript.forEach(tmpOut);
// 将数据填充到Allocation中
tmpOut.copyTo(outputBitmap);
// 返回模糊后的bitmap对象
return outputBitmap;
}
}
使用实例:
CoordinatorLayout layout = (CoordinatorLayout) findViewById(R.id.bg);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.sss);
Bitmap blurBitmap = BlurBitmap.blur(this, bitmap);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackground(new BitmapDrawable(getResources(), blurBitmap));
}
效果
原图:
模糊后:
注意事项: