android 毛玻璃模糊效果背景实现

今天我们来简单了解一下Android开发上的几种图片高斯模糊技术的效果实现



1,首先看实现前效果图(这图别介意,这不是重点):


2,高斯模糊实现后效果图 :

,利用 RenderScript接口 

RenderScript 是一种低级的高性能编程语言,用于3D渲染和处理密集型计算,RenderScript 也是3.0 以后才开始引用,所以需要进行一定的兼容性,从代码实现上来说是最简单也相对高效的实现. 在此过程中会遇到问题比如当模糊半径 (radius)变大后会直接出现计算性能问题. 模糊半径不能大于25,因此, 直接使用ScriptIntrinsicBlur也不能得到模糊程度较高的图片),下面看代码。

1,Activity 文件

public class MainActivity extends Activity {

	private ImageView iv_image;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv_image = (ImageView) findViewById(R.id.iv_image);
		iv_image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new MakeBitmapAsyncTask().execute();//建议用AsynTask或者其他机制来处理
			}
		});
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	private Bitmap blur(Bitmap bitmap, View view) {
		// 把 bitmap的尺寸缩小到原图的1/8 这时候bitmap在模糊处理过程中先被缩小然再放大
		float scaleFactor = 8;
		float radius = 3;
		Bitmap overlayBmp = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor),
				(int) (view.getMeasuredHeight() / scaleFactor), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(overlayBmp);
		canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor);
		canvas.scale(1 / scaleFactor, 1 / scaleFactor);
		Paint paint = new Paint();
		// 这里bitmap缩放时 加FILTER_BITMAP_FLAG会更加顺畅
		paint.setFlags(Paint.FILTER_BITMAP_FLAG);
		canvas.drawBitmap(bitmap, 0, 0, paint);
		// 通过 RenderScript 调用底层接口来实现高斯模糊计算
		RenderScript rs = RenderScript.create(MainActivity.this);
		Allocation overlayAlloc = Allocation.createFromBitmap(rs, overlayBmp);
		// 有个缺点那就是 ScriptIntrinsicBlur只支持API17以上
		ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, overlayAlloc.getElement());
		blur.setInput(overlayAlloc);
		blur.setRadius(radius);
		blur.forEach(overlayAlloc);
		overlayAlloc.copyTo(overlayBmp);
		rs.destroy();
		return overlayBmp;
	}

	private class MakeBitmapAsyncTask extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... params) {
			View view = getWindow().getDecorView();
			view.setDrawingCacheEnabled(true);
			view.buildDrawingCache(true);
			Bitmap bitmap = view.getDrawingCache();
			return blur(bitmap, view);
		}
		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			iv_image.setBackground(new BitmapDrawable(getResources(), result));
		}
	}
}

2,activity_main.xml 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
	     android:id="@+id/iv_image"
	     android:layout_width="match_parent"
	     android:layout_height="match_parent"
	     android:scaleType="centerCrop"
	     android:background="@drawable/image" />
        
</RelativeLayout>
,使用 FashBlur 实现

FastBlur进行模糊操作比Renderscript 要快一些,因为FastBlur在进行bitmap复制操作时还同时进行其他操作,所以说节省了一些时间

1,Activity 文件

public class MainActivity2 extends Activity {

	private ImageView iv_image2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main2);
		iv_image2 = (ImageView) findViewById(R.id.iv_image2);
		iv_image2.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

			@Override
			public boolean onPreDraw() {
				iv_image2.getViewTreeObserver().removeOnPreDrawListener(this);
				iv_image2.buildDrawingCache();
				Bitmap bmp = iv_image2.getDrawingCache();
				blur(bmp, iv_image2);
				return true;
			}
		});
	}

	private void blur(Bitmap bkg, View view) {
		float scaleFactor = 8;
		float radius = 3;
		Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor),
				(int) (view.getMeasuredHeight() / scaleFactor), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(overlay);
		canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor);
		canvas.scale(1 / scaleFactor, 1 / scaleFactor);
		Paint paint = new Paint();
		paint.setFlags(Paint.FILTER_BITMAP_FLAG);
		canvas.drawBitmap(bkg, 0, 0, paint);
		//然后通过FastBlur.doBlur() 实现处理
		overlay = FastBlur.doBlur(overlay, (int) radius, true);
		view.setBackground(new BitmapDrawable(getResources(), overlay));
	}
}
2activity_main2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
	     android:id="@+id/iv_image2"
	     android:layout_width="match_parent"
	     android:layout_height="match_parent"
	     android:scaleType="centerCrop"
	     android:background="@drawable/image" />
        
</RelativeLayout>
3,FastBlur.java 
public class FastBlur {

    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++) {
                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);
        return (bitmap);
    }
}


其实模糊算法在 java层实现对性能有影响,如果你想做到高效率的模糊效果,那就必须用到JNI来实现


好了,如果有兴趣可以看看这些文章或许对你有帮助
http://blog.csdn.net/grp0916/article/details/50494712

https://github.com/kikoso/android-stackblur

https://github.com/harism/android_anndblur

https://github.com/500px/500px-android-blur

阅读更多
个人分类: android 开发
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

android 毛玻璃模糊效果背景实现

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭