需要使用v8库

模糊效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static Drawable createBlurredImageFromBitmap(Bitmap bitmap, Context context, int inSampleSize) {
RenderScript rs = RenderScript.create(context);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
Bitmap blurTemplate = BitmapFactory.decodeStream(bis, null, options);
final android.support.v8.renderscript.Allocation input = android.support.v8.renderscript.Allocation.createFromBitmap(rs, blurTemplate);
final android.support.v8.renderscript.Allocation output = android.support.v8.renderscript.Allocation.createTyped(rs, input.getType());
final android.support.v8.renderscript.ScriptIntrinsicBlur script = android.support.v8.renderscript.ScriptIntrinsicBlur.create(rs, android.support.v8.renderscript.Element.U8_4(rs));
script.setRadius(8f);
script.setInput(input);
script.forEach(output);
output.copyTo(blurTemplate);
return new BitmapDrawable(context.getResources(), blurTemplate);
}

较耗时,使用异步操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private class setBlurredAlbumArt extends AsyncTask<Bitmap, Void, Drawable> {
@Override
protected Drawable doInBackground(Bitmap... loadedImage) {
Drawable drawable = null;
try {
drawable = ImageUtils.createBlurredImageFromBitmap(loadedImage[0], getActivity(), 6);
} catch (Exception e) {
e.printStackTrace();
}
return drawable;
}
@Override
protected void onPostExecute(Drawable result) {
if (result != null) {
if (mBlurredArt.getDrawable() != null) {
final TransitionDrawable td =
new TransitionDrawable(new Drawable[]{
mBlurredArt.getDrawable(),
result
});
mBlurredArt.setImageDrawable(td);
td.startTransition(200);
} else {
mBlurredArt.setImageDrawable(result);
}
}
}
@Override
protected void onPreExecute() {
}
}