BaseRender
import android.graphics.Bitmap;
public interface BaseRender {
public abstract void blur(float radius, Bitmap in, Bitmap out);
public abstract void destory();
}
Blur
public class Blur {
private static final float BITMAP_SCALE_NOMAL = 0.8f;
private static final float BLUR_RADIUS_NOMAL = 12.0f;
public static final float BITMAP_SCALE_FAST = 0.2f;
public static final float BLUR_RADIUS_FAST = 5.0f;
private boolean USE_JNI = false;
private BaseRender mRender;
private static Blur instance;
public static Blur getInstance(Context context) {
if(instance == null)
instance = new Blur(context);
return instance;
}
private Blur(Context context) {
mRender = new ScriptIntrinsicBlurRender(context);
}
public Bitmap blur(Bitmap image, boolean fast) {
float scale = BITMAP_SCALE_NOMAL;
float radius = BLUR_RADIUS_NOMAL;
if (fast) {
scale = BITMAP_SCALE_FAST;
radius = BLUR_RADIUS_FAST;
}
int width = Math.round(image.getWidth() * scale);
int height = Math.round(image.getHeight() * scale);
Bitmap bitmap = Bitmap.createScaledBitmap(image, width, height, true);
Bitmap outputBitmap = bitmap.copy(bitmap.getConfig(), true);
mRender.blur(radius, bitmap, outputBitmap);
bitmap.recycle();
return outputBitmap;
}
public void destory() {
if (mRender != null) {
mRender.destory();
}
}
}
RSRender
public abstract class RSRender implements BaseRender {
protected RenderScript rs;
public RSRender(Context ctx) {
rs = RenderScript.create(ctx);
}
@Override
public void blur(float radius, Bitmap in, Bitmap out) {
Allocation tmpIn = Allocation.createFromBitmap(rs, in);
Allocation tmpOut = Allocation.createFromBitmap(rs, out);
blur(radius, tmpIn, tmpOut);
tmpOut.copyTo(out);
tmpIn.destroy();
tmpOut.destroy();
}
public abstract void blur(float radius, Allocation tmpIn, Allocation tmpOut);
@Override
public void destory() {
if (rs != null) rs.destroy();
}
}
ScriptIntrinsicBlurRender
public class ScriptIntrinsicBlurRender extends RSRender {
private ScriptIntrinsicBlur theIntrinsic;
public ScriptIntrinsicBlurRender(Context context) {
super(context);
theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
}
@Override
public void blur(float radius, Allocation tmpIn, Allocation tmpOut) {
theIntrinsic.setRadius(radius);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
}
@Override
public void destory() {
super.destory();
theIntrinsic.destroy();
}
}
调用方式
Bitmap bitmap = Blur.getInstance(context).blur(bitmap, false);