有時候我們需要將一個佈局文件轉換成圖片。
工具代碼
//把佈局變成Bitmap
private Bitmap getViewBitmap(View addViewContent) {
addViewContent.setDrawingCacheEnabled(true);
addViewContent.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
addViewContent.layout(0, 0,
addViewContent.getMeasuredWidth(),
addViewContent.getMeasuredHeight());
addViewContent.buildDrawingCache();
Bitmap cacheBitmap = addViewContent.getDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
return bitmap;
}
佈局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/wb_location_map_marker_name"
android:background="#FFFFFF"
android:text="李三" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/jy_icon_gcoding" />
</LinearLayout>
使用操作記錄
LayoutInflater inflater = getLayoutInflater();
View view=inflater.inflate(R.layout.wb_location_map_marker,null);
TextView txt=(TextView)view.findViewById(R.id.wb_location_map_marker_name);
txt.setText(content);
Bitmap viewBitmap=getViewBitmap(view);