[TOC]
Bitmap作为背景图在应用中多采用虚化或者加半透明黑色蒙版为主,特别是针对主题颜色较亮的图片,可以有效避免喧宾夺主。Bitmap作为背景图加载及虚化主要包含如下步骤。
读取Bitmap图片
/**
*以文件流的方式,假设在sdcard下有 test.png图片
*/
FileInputStream fis = new FileInputStream("/sdcard/test.png");Bitmap bitmap = BitmapFactory.decodeStream(fis);
/**
*以R文件的方式,假设 res/drawable下有 test.jpg文件
*/
Bitmap bitmap = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.test);
/**
*以ResourceStream的方式,但不用到R文件
*/
Bitmap.bitmap = BitmapFactory.decodeStream(getClass.getResourceAsStream(“/res/drawable/test.png”)
使用如下方式加载图片
detailView=(ImageView)findViewById(R.id.detailView);
detailView.setBackgroundResource(R.drawable.more_info);
detailView.setImageResource(R.drawable.more_info);
会导致OOM,android对于直接通过资源id载入的资源需做cache,下次再需要此资源的时候直接从cache中得到。但这样做也造成了用过的资源都会在内存中,这样的设计不是很适合使用了很多大图片资源的应用,这样累积下来应用的内存峰值是很高的。
当使用诸如
imageView.setBackgroundResource
imageView.setImageResource
BitmapFactory.decodeResource
这样的方法来设置一张大图片时,在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存。因此,改用先通过BitmapFactory.decodeStream方法,创建出一个bitmap,再将其设为ImageView的 source,decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,无需再使用java层的createBitmap,从而节省了java层的空间。如果在读取时加上图片的Config参数,可以有效减少加载的内存,从而有效阻止抛OOM异常。
Bitmap设置虚化效果
实际使用中,可以针对bitmap做如下操作
public static Bitmap rsBlur(Context context, Bitmap source, int radius){
Bitmap inputBmp = source;
RenderScript renderScript = RenderScript.create(context);
final Allocation input = Allocation.createFromBitmap(renderScript,inputBmp);
final Allocation output = Allocation.createTyped(renderScript,input.getType());
ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
scriptIntrinsicBlur.setInput(input);
scriptIntrinsicBlur.setRadius(radius);
scriptIntrinsicBlur.forEach(output);
output.copyTo(inputBmp);
renderScript.destroy();
return inputBmp;
}
RenderScript是Google在API11中引入的类,可看作业android内置的图片处理框架(区别于Glide等图片处理框架,RenderScript注重于图片的处理而不是加载)。RenderScript实际操作基于RenderScript Intrinsics,一些可以帮助RenderScript快速实现各种图片处理的操作类。该类包含诸多操作功能,比如利用ScriptIntrinsicBlur,就可以简单高效地实现高斯模糊效果,可通过参数radius设置虚化的程度。
bitmap设置背景虚化
//options 包含新建Bitmap图片资源的相关设置
BitmapFactory.Options options = new BitmapFactory.Options();
//基于options设置新建Bitmap资源
Bitmap bitmap1 = BitmapFactory.decodeResource(MainActivity.this.getResources(), R.drawable.main_bg,options);
//获取经虚化的Bitmap资源
Bitmap rsBitmap = BlurUtil.rsBlur(MainActivity.this,bitmap,25);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), rsBitmap);
//为目标控件设置虚化背景
ImageView background = findViewById(R.id.main_bg);
background.setBackground(bitmapDrawable);
1920*1080的原始图片未经压缩读取时间可能会超过1s,使用该图片作为背景图片加载时会有明显的卡顿。此时就需要设置BitmapFactory.Options实现对待加载图片的压缩。可参照https://blog.csdn.net/u012124438/article/details/66087785逐步优化Bitmap加载。对于加载图片较多较频繁的功能,建议使用第三方的图片加载框架,如Glide或者Picasso。
仅仅实现设置虚化背景的功能,那么到这里就足够了。更详细的Bitmap虚化算法及原理可以参看下面的代码,该段代码引用自
https://github.com/zuiwuyuan/FastBlur_VoiceChat/blob/master/app/src/main/java/com/lnyp/voicechat/FastBlur.java
和上文提到的scriptIntrinsicBlur方法略有不同,但原理是一致的。
bitmap虚化基本原理
public class BlurUtil {
private static final String TAG = BlurUtil.class.getSimpleName();
/**
* 对图片进行毛玻璃化
* @param sentBitmap 位图
* @param radius 虚化程度
* @param canReuseInBitmap 是否重用
* @return 位图
*/
public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {
Bitmap bitmap;
if (canReuseInBitmap) {
bitmap = sentBitmap;
} else {
bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
}
if (radius < 1) {
return (null);
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (i / divsum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
// print("虚化后 ",bitmap);
return (bitmap);
}
/**
* 对图片进行毛玻璃化
* @param originBitmap 位图
* @param scaleRatio 缩放比率
* @param blurRadius 毛玻璃化比率,虚化程度
* @return 位图
*/
public static Bitmap doBlur(Bitmap originBitmap, int scaleRatio, int blurRadius){
// print("原图::",originBitmap);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(originBitmap,
originBitmap.getWidth() / scaleRatio,
originBitmap.getHeight() / scaleRatio,
false);
Bitmap blurBitmap = doBlur(scaledBitmap, blurRadius, false);
scaledBitmap.recycle();
return blurBitmap;
}
/**
* 对图片进行 毛玻璃化,虚化
* @param originBitmap 位图
* @param width 缩放后的期望宽度
* @param height 缩放后的期望高度
* @param blurRadius 虚化程度
* @return 位图
*/
public static Bitmap doBlur(Bitmap originBitmap,int width,int height,int blurRadius){
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(originBitmap, width, height);
Bitmap blurBitmap = doBlur(thumbnail, blurRadius, true);
thumbnail.recycle();
return blurBitmap;
}
}
//省略布局代码...
//使用时,直接调用BlurUtil中的doBlur方法
Bitmap bgbm = BlurUtil.doBlur(music.thumbBitmap,10,5);
需要注意的是,此处doBlur有两个重载,可根据需要设置图片的缩放比例.这种方式和前文通过BitmapFactory.Options设置Bitmap取样格式的效果是一致的,都是为了减小Bitmap加载的资源消耗,提高加载效率。