Activity、View 转Bitmap,拿走,直接用,不谢。
注意:背景需要自己处理。
/**
* author: vector.huang
* date: 2019/04/15 14:19
*/
public class View2BitmapUtil {
/**
* 指定Activity的Bitmap
*/
public static Bitmap getBitmap(Activity activity, boolean needStatusBar) {
//获取需要显示的View
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
// 获取屏幕长和高
Point size = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(size);
int y = 0;
int height = size.y;
if (!needStatusBar) {
//状态栏
//获取状态栏高度
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
y = frame.top;
height -= frame.top;
}
Bitmap b = Bitmap.createBitmap(bitmap, 0, y, size.x, height);
view.destroyDrawingCache();
return b;
}
/**
* 已经显示的view转bitmap,获取整个View 的内容
*/
public static Bitmap getAllBitmap(View view) {
//布局,为了呈现整个View,所以高度设置尽量大,不然可能只看到一半
//假装父View高,整个整个View 就会全部显示了
int width = view.getWidth();
int height = view.getHeight();
view.layout(0, 0, width, 10000_0000);
//计算
int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(10000_0000, View.MeasureSpec.AT_MOST);
view.measure(measuredWidth, measuredHeight);
//再次布局,使其刚刚好
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
//转bitmap
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = getBitmap(view);
//复原
view.layout(0, 0, width, height);
view.measure(width, height);
return bitmap;
}
/**
* 已经显示的view转bitmap,获取可见部分
*/
public static Bitmap getBitmap(View v) {
int w = v.getWidth();
int h = v.getHeight();
Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
v.layout(0, 0, w, h);
v.draw(c);
return bmp;
}
/**
* 可以完整地获取布局文件的Bitmap
*/
public static Bitmap getBitmap(Activity activity, @LayoutRes int layoutRes, int width,
OnMeasuredListener onMeasuredListener) {
//获取View
View view = LayoutInflater.from(activity).inflate(layoutRes, null);
//布局,为了呈现整个View,所以高度设置尽量大,不然可能只看到一半
//假装父View高,整个整个View 就会全部显示了
view.layout(0, 0, width, 10000_0000);
//计算
int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(10000_0000, View.MeasureSpec.AT_MOST);
view.measure(measuredWidth, measuredHeight);
//再次布局,使其刚刚好
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
//这里可以填充内容
if (onMeasuredListener != null) {
onMeasuredListener.onMeasured(view);
}
//转bitmap
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
return getBitmap(view);
}
public interface OnMeasuredListener {
void onMeasured(View v);
}
}
网友评论