一、获取View快照
方法1、已绘制到Window的View
public static Bitmap getBitmapFromView(View view) {
Bitmap bitmap = null;
//开启view缓存bitmap
view.setDrawingCacheEnabled(true);
//设置view缓存Bitmap质量
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
//获取缓存的bitmap
Bitmap cache = view.getDrawingCache();
if (cache != null && !cache.isRecycled()) {
bitmap = Bitmap.createBitmap(cache);
}
//销毁view缓存bitmap
view.destroyDrawingCache();
//关闭view缓存bitmap
view.setDrawingCacheEnabled(false);
return bitmap;
}
方法2、任意View,如 getBitmapFromView(LayoutInflater.from(context).inflate(R.layout.test, null), 0xFFFFFFFF)
/**
* 获取未依附到window的View的快照
*
* @param view View
* @param bgColor 画布背景色
* @return Bitmap
*/
public static Bitmap getBitmapFromView(View view, int bgColor) {
if (view == null) {
return null;
}
int viewWidth = view.getWidth();
int viewHeight = view.getHeight();
if (viewWidth == 0 && viewHeight == 0) {
int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
viewWidth = view.getMeasuredWidth();
viewHeight = view.getMeasuredHeight();
view.layout(0, 0, viewWidth, viewHeight);
}
Bitmap screenshot = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(screenshot);
c.drawColor(bgColor);
view.draw(c);
return screenshot;
}
持续更新中...