将自定义view填充数据后,转成bitmap,填充到ImageView中
里面是RecycleView用于填充数据,ConstraintLayout是为了设置宽高生效,多加了层布局
test.xml
View.MeasureSpec.EXACTLY 适用match_parent
View.MeasureSpec.AT_MOST 适用wrap_content
注意:transViewToBitmap中传的View一定是match_parent
getMaxSize中传的View一定是wrap_content
/**
* 自定义view转图片
*
* @param view
* @return
*/
public static Bitmap transViewToBitmap(View view, int size) {
int measuredWidth = View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY);
view.measure(measuredWidth, measuredHeight);
int w = view.getMeasuredWidth();
int h = view.getMeasuredHeight();
Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.drawColor(Color.TRANSPARENT); //如果不设置canvas画布为白色,则生成透明
view.layout(0, 0, w, h);
view.draw(canvas);
return bmp;
}
/**
* 获取自适应view最大高度/宽度
*
* @param view
* @return
*/
public static int getMaxSize(View view) {
int measuredWidth = View.MeasureSpec.makeMeasureSpec(10000, View.MeasureSpec.AT_MOST);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(10000, View.MeasureSpec.AT_MOST);
view.measure(measuredWidth, measuredHeight);
int w = view.getMeasuredWidth();
int h = view.getMeasuredHeight();
return w > h ? w : h;
}
View view = LayoutInflater.from(context).inflate(R.layout.layout_marker_combine, null, false);
RecyclerView recyclerView = view.findViewById(R.id.recycleview);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
//填充RecycleView数据而已
TestAdapter adapter = new TestAdapter();
adapter.bindToRecyclerView(recyclerView);
//获取内部RecycleView宽高最大值作为BitMap的宽高,size也可直接写死,我的需求是图片宽高一样
int size = BitmapUtil.getMaxSize(recyclerView);
BitMap bitmap = BitmapUtil.transViewToBitmap(view,size));