需求
把UI布局转换成图片保存到本地或者分享出去。
Activity 布局
测量过UI布局(已经绘制显示屏幕上)
public static Bitmap convertViewToBitmap(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();
return bitmap;
}
未测量过UI布局(未显示屏幕上)
public static Bitmap convertMeasureViewToBitmap(View view) {
view.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
view.layout(0,0,view.getMeasuredWidth(),view.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.scale(1, 1);
view.draw(canvas);
return bitmap;
}
WebView 截图
第一种
//获取webview缩放率
float scale = wv_capture.getScale();
//得到缩放后webview内容的高度
int webViewHeight = (int) (wv_capture.getContentHeight()*scale);
Bitmap bitmap = Bitmap.createBitmap(wv_capture.getWidth(),webViewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//绘制
wv_capture.draw(canvas);
第二种
通过获取当前window的DecorView,然后绘制Bitmap对象。
View view = context.getWindow().getDecorView();
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);