产品需求:
每个界面调起需要设置前一个界面的高斯模糊为背景,经解析大概是需要三步:
1.在Activity的onCreate中截取图片
2.对截取到图片进行高斯模糊
3.设置高斯模糊后的图片为Activity的background
总结了网上的一些方法使用了MediaProjectionManager+EasyBlur,经测试截屏+模糊需要300~600ms,时间有点长慎重使用。
下面介绍一种截屏方法:使用MediaProjectionManager
1.添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
2.获取MediaProjectionManager对象
MediaProjectionManager mediaProjectionManager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (mediaProjectionManager != null) {
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), 1);
}
3.onActivityResult中结果反馈并调用截屏
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
//开始截屏
startScreenShot(data);
}
}
4.获取截屏后图片并进行高斯模糊
public void startScreenShot(Intent data) {
ScreenShotHelper screenShotHelper = new ScreenShotHelper(MainActivity.this
, RESULT_OK
, data
, getScreenWidth()
, bitmap -> {
//对截屏后图片进行高斯模糊
Bitmap blurBitmap = EasyBlur.with(MainActivity.this)
.bitmap(bitmap)
.radius(2)
.blur();
});
screenShotHelper.startScreenShot();
}
private int getScreenWidth() {
int dpi = 0;
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
try {
@SuppressWarnings("rawtypes")
Class c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
dpi = dm.widthPixels;
} catch (Exception e) {
e.printStackTrace();
}
return dpi;
}
5.截屏类ScreenShotHelper
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.AsyncTask;
import android.os.Handler;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
public class ScreenShotHelper {
private static final String TAG = "ScreenShotHelper";
private final SoftReference<Context> mRefContext;
private OnScreenShotListener mOnScreenShotListener;
private ImageReader mImageReader;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
private int mScreenWidth;
public ScreenShotHelper(Context context, int resultCode, Intent data, int width
, OnScreenShotListener onScreenShotListener) {
this.mOnScreenShotListener = onScreenShotListener;
this.mRefContext = new SoftReference<>(context);
this.mScreenWidth = width;
mMediaProjection = getMediaProjectionManager().getMediaProjection(resultCode, data);
mImageReader = ImageReader.newInstance(width
, getScreenHeight(), PixelFormat.RGBA_8888, 1);
}
private int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
public void startScreenShot() {
createVirtualDisplay();
Handler handler = new Handler();
handler.postDelayed(() -> new CreateBitmapTask(this).execute(), 100);
}
private MediaProjectionManager getMediaProjectionManager() {
return (MediaProjectionManager) getContext().getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
}
private void createVirtualDisplay() {
mVirtualDisplay = mMediaProjection.createVirtualDisplay(
"screen-mirror", mScreenWidth, getScreenHeight(),
Resources.getSystem().getDisplayMetrics().densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mImageReader.getSurface(), null, null
);
}
private Context getContext() {
return mRefContext.get();
}
public interface OnScreenShotListener {
void onFinish(Bitmap bitmap);
void onFailed();
}
private static class CreateBitmapTask extends AsyncTask<Image, Void, Bitmap> {
private ScreenShotHelper helper;
private Image image;
private Bitmap bitmap;
CreateBitmapTask(ScreenShotHelper helper) {
WeakReference<ScreenShotHelper> weakReference = new WeakReference<>(helper);
this.helper = weakReference.get();
}
@Override
protected Bitmap doInBackground(Image... params) {
LogUtil.i(TAG, "ScreenShot startScreenShot");
image = helper.mImageReader.acquireLatestImage();
if (image == null) {
LogUtil.E(TAG, "ScreenShot image is null");
return null;
}
try {
int width = image.getWidth();
int height = image.getHeight();
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride
, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
image.close();
helper.mImageReader.close();
LogUtil.i(TAG, "ScreenShot endScreenShot");
} catch (Exception e) {
e.printStackTrace();
LogUtil.E(TAG, "ScreenShot failed: " + e.getMessage());
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap == null) {
LogUtil.E(TAG, "ScreenShot bitmap is null");
if (helper.mOnScreenShotListener != null) {
helper.mOnScreenShotListener.onFailed();
}
return;
}
if (helper.mVirtualDisplay != null) {
helper.mVirtualDisplay.release();
helper.mVirtualDisplay = null;
}
if (helper.mMediaProjection != null) {
helper.mMediaProjection.stop();
helper.mMediaProjection = null;
}
if (helper.mOnScreenShotListener != null) {
helper.mOnScreenShotListener.onFinish(bitmap);
}
}
}
}
6.高斯模糊类EasyBlur,网上通用,这里拿来用一下
import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.util.Log;
public class EasyBlur {
private static final String TAG = "EasyBlur";
private static final float SCALE = 1 / 8.0F;//default scale
private static volatile EasyBlur singleton = null;
private Bitmap mBitmap;
private int mRadius = 0;
private float mScale = SCALE;
private Context mContext;
private BlurPolicy mPolicy = BlurPolicy.RS_BLUR;//默认使用rs 模糊图片
private EasyBlur(Context context) {
this.mContext = context.getApplicationContext();
}
/**
* 单例
*
* @param context 上下文
* @return 单例模式 返回
*/
public static EasyBlur with(Context context) {
if (singleton == null) {
synchronized (EasyBlur.class) {
if (singleton == null) {
singleton = new EasyBlur(context);
}
}
}
return singleton;
}
/**
* 使用RenderScript 模糊图片
*
* @param context 上下文
* @param source bitmap资源
* @return 返回bitmap对象
*/
private static Bitmap rsBlur(Context context, Bitmap source, int radius, float scale) {
Log.i(TAG, "origin size:" + source.getWidth() + "*" + source.getHeight());
int width = Math.round(source.getWidth() * scale);
int height = Math.round(source.getHeight() * scale);
Bitmap inputBmp = Bitmap.createScaledBitmap(source, width, height, false);
RenderScript renderScript = RenderScript.create(context);
Log.i(TAG, "scale size:" + inputBmp.getWidth() + "*" + inputBmp.getHeight());
// Allocate memory for Renderscript to work with
final Allocation input = Allocation.createFromBitmap(renderScript, inputBmp);
final Allocation output = Allocation.createTyped(renderScript, input.getType());
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
scriptIntrinsicBlur.setInput(input);
// Set the blur radius
scriptIntrinsicBlur.setRadius(radius);
// Start the ScriptIntrinisicBlur
scriptIntrinsicBlur.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(inputBmp);
renderScript.destroy();
return inputBmp;
}
/**
* Stack Blur v1.0 from
* http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
* Java Author: Mario Klingemann <mario at quasimondo.com>
* http://incubator.quasimondo.com
* <p>
* created Feburary 29, 2004
* Android port : Yahel Bouaziz <yahel at kayenko.com>
* http://www.kayenko.com
* ported april 5th, 2012
* <p>
* This is a compromise between Gaussian Blur and Box blur
* It creates much better looking blurs than Box Blur, but is
* 7x faster than my Gaussian Blur implementation.
* <p>
* I called it Stack Blur because this describes best how this
* filter works internally: it creates a kind of moving stack
* of colors whilst scanning through the image. Thereby it
* just has to add one new block of color to the right side
* of the stack and remove the leftmost color. The remaining
* colors on the topmost layer of the stack are either added on
* or reduced by one, depending on if they are on the right or
* on the left side of the stack.
* <p>
* If you are using this algorithm in your code please add
* the following line:
* Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
*/
private static Bitmap fastBlur(Bitmap sentBitmap, float scale, int radius) {
int width = Math.round(sentBitmap.getWidth() * scale);
int height = Math.round(sentBitmap.getHeight() * scale);
sentBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);
Bitmap 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];
Log.e("pix", w + " " + h + " " + pix.length);
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;
}
}
Log.e("pix", w + " " + h + " " + pix.length);
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return (bitmap);
}
public Bitmap blur() {
if (mBitmap == null) {
throw new RuntimeException("Bitmap can not be null");
}
if (mRadius == 0) {
throw new RuntimeException("radius must > 0");
}
// support library running on 2.3(API 9) and higher 算法
if (mPolicy == BlurPolicy.FAST_BLUR) {
LogUtil.i(TAG, "blur fast algorithm");
return fastBlur(mBitmap, mScale, mRadius);
} else {
LogUtil.i(TAG, "blur render script algorithm");
return rsBlur(mContext, mBitmap, mRadius, mScale);
}
}
/**
* 模糊的算法策略
*
* @param policy 算法策略
* @return 返回EasyBlur
*/
public EasyBlur policy(BlurPolicy policy) {
this.mPolicy = policy;
return this;
}
/**
* 模糊的Bitmap
*
* @param bitmap bitmap对象
* @return 返回模糊之后对象
*/
public EasyBlur bitmap(Bitmap bitmap) {
this.mBitmap = bitmap;
return this;
}
/**
* 缩放的系数
*
* @param scale 系数 0-1之间
* @return 返回系数
*/
public EasyBlur scale(int scale) {
this.mScale = 1.0f / scale;
return this;
}
/**
* 模糊的半径,0-25
*
* @param radius 模糊半径
* @return 返回radius参数
*/
public EasyBlur radius(int radius) {
this.mRadius = radius;
return this;
}
public enum BlurPolicy {
RS_BLUR,
FAST_BLUR
}
}
总结:
上述方法截屏时会有一个弹窗,如果你可以改系统代码,可以完全去掉这个弹窗。