1、 获取可视控件、布局的截图
1.1 方法:view.getDrawingCache()
1.2 demo:获取屏幕截屏
public static Bitmap screenShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = ScreenUtils.getScreenWidth();
int height = ScreenUtils.getScreenHeight();
Bitmap bp = null;
bp = Bitmap.createScaledBitmap(bitmap, width, height - statusBarHeight,true);
view.destroyDrawingCache();
view.setSystemUiVisibility(View.VISIBLE);
return bp;
}
2、 获取不可视控件、布局的截图
2.1 方法:Bitmap.createBitmap()
2.2 demo:把一个xml布局文件转成bitmap
private Bitmap createBitmapByView() {
View view = LayoutInflater.from(activity).inflate(R.layout.img_qrcode, null, false);
WindowManager manager = activity.getWindowManager();
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
int measureWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measureHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);
view.measure(measureWidth, measureHeight);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
3、view.getDrawingCache() 为 null 解决方案
public static BitmapWithHeight getSimpleViewToBitmap(final View view, int width) throws OutOfMemoryError {
if (view.getWidth() <= 0 || view.getHeight() <= 0) {
view.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}
view.destroyDrawingCache();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap map = view.getDrawingCache();
if (view.getHeight() > 0 && map == null)
map = getViewBitmap(view);
return new BitmapWithHeight(map, view.getMeasuredWidth(), view.getMeasuredHeight());
}
public static Bitmap getViewBitmap(View view) {
Bitmap bitmap;
if (view.getWidth() > 0 && view.getHeight() > 0)
bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
else if (view.getMeasuredWidth() > 0 && view.getMeasuredHeight() > 0)
bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
else
bitmap = Bitmap.createBitmap(com.blankj.utilcode.utils.ScreenUtils.getScreenWidth(), com.blankj.utilcode.utils.ScreenUtils.getScreenHeight() * 2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
|