使用view生成图片看起来不复杂,实际操作各种坑,记录一下吧!
通过view来生成bitmap,这里要特别注意yourview应该是在你正常显示页面范围内, 把yourview设置为invisible即可, 通过inflater方式生成的view和设置为gone的方式经测试都不行。
//调用方式:
var bitmap= createBitmap3(yourview, ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
public static Bitmap createBitmap3(View v, int width, int height) {
//测量使得view指定大小
int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
v.measure(measuredWidth, measuredHeight);
//调用layout方法布局后,可以得到view的尺寸大小
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
c.drawColor(Color.WHITE);
v.draw(c);
return bmp;
}