生成图片代码如下,不需要将布局显示在屏幕上:
private static Bitmap generalBitmap(ViewGroup viewGroup, int width, int height) {
// width and height must >0
if (width <= 0 || height <= 0) {
return null;
}
viewGroup.measure(width, height);
viewGroup.layout(0, 0, viewGroup.getMeasuredWidth(), viewGroup.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(viewGroup.getWidth(), viewGroup.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
viewGroup.draw(canvas);
return bitmap;
}
在宽高确定的情况下直接传入宽高的值,通过View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY) 转换一下;例如宽为屏幕的宽screenWidth,则将得到的width传入generalBitmap中:
int width = View.MeasureSpec.makeMeasureSpec(screenWidth, View.MeasureSpec.EXACTLY);
在宽或高不确定的情况下,比如TextView不确定多高的情况,通过View.measure(0,0)测量一下,得到宽或高传入到generalBitmap中即可;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
viewGroup.getChildAt(i).measure(0, 0); // UNSPECIFIED
width += viewGroup.getChildAt(i).getMeasuredWidth();
height += viewGroup.getChildAt(i).getMeasuredHeight();
}
Demo