起因
有一个需求,需要将xml布局,生成成一张图片。这样可以将图片导出保存,或者在ImageView上自适应的展示。(在布局多变的情况下,不用一直改字体大小啥的)。
百度了一圈,都达不到想要的,然后自己写了一个
功能
- 将xml布局加载成Bitmap
- 将随便什么View加载成Bitmap
效果
将这个xml,加载生成一个bitmap,然后加载到ImageView上,这样可以随意改变大小,自适应展示。或者可以保存图片到本地。
代码
使用
fun loadImageView(){
var bitmap= ImageUtils.loadBitmap(this,R.layout.window_coupon)
iv_image.setImageBitmap(bitmap)
}
复制代码
工具类
public class ImageUtils {
/**
* 将 Bitmap 保存到SD卡
*
* @param context
* @param mybitmap
* @param name
* @return
*/
public static boolean saveBitmapToSdCard(Context context, Bitmap mybitmap, String name) {
boolean result = false;
//创建位图保存目录
String path = Environment.getExternalStorageDirectory() + "/1000ttt/";
File sd = new File(path);
if (!sd.exists()) {
sd.mkdir();
}
File file = new File(path + name + ".jpg");
FileOutputStream fileOutputStream = null;
if (!file.exists()) {
try {
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
fileOutputStream = new FileOutputStream(file);
mybitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
//update gallery
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
result = true;
} else {
Toast.makeText(context, "不能读取到SD卡", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static View loadView(Context context, int viewResId) {
if (context == null || viewResId <= 0) return null;
FrameLayout frameLayout = new FrameLayout(context);
View view = LayoutInflater.from(context).inflate(viewResId, frameLayout, false);
return view;
}
/**
* 从静态资源中,渲染并导出一张Bitmap图片
*
* @param context
* @param viewResId
* @return
*/
public static Bitmap loadBitmap(Context context, int viewResId) {
if (context == null || viewResId <= 0) return null;
return loadBitmap(loadView(context, viewResId));
}
private static Bitmap loadBitmap(View v) {
int measuredWidth = View.MeasureSpec.makeMeasureSpec(v.getLayoutParams().width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(v.getLayoutParams().height, View.MeasureSpec.EXACTLY);
v.measure(measuredWidth, measuredHeight);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache();
Bitmap bitmap = v.getDrawingCache();
return bitmap;
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}
复制代码