将自定义view填充数据后,转成bitmap,填充到ImageView中
1.自定义布局
里面是RecycleView用于填充数据,ConstraintLayout是为了设置宽高生效,多加了层布局
test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycleview"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:nestedScrollingEnabled="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
2.BitMapUtils工具类
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;
}
3.
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));