我需要将准备好的布局保存到外部存储器中的图像文件
目前我已尝试获取布局,启用绘图缓存,传递到位图并保存在文件中
LayoutInflater inflate = LayoutInflater.from(this);
View view = inflate.inflate(R.layout.to_send, null);
view.setDrawingCacheEnabled(true);
Bitmap returnedBitmap;
if (view.getMeasuredHeight() <= 0) {
view.measure(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
returnedBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
returnedBitmap.recycle();
Canvas c = new Canvas(returnedBitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(c);
}
else {
returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
}
//Bitmap bitmap = content.getDrawingCache();
File fPath = Environment.getExternalStorageDirectory();
File f = new File(fPath + "Send.png");
try {
if (!f.exists()) {
f.createNewFile();
}
FileOutputStream strm = new FileOutputStream(f);
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 80, strm);
strm.close();
//content.invalidate();
}
catch (Exception e){
e.printStackTrace();
} finally {
view.setDrawingCacheEnabled(false);}
答案 0 :(得分:1)
如果有人遇到同样的问题。这解决了我的问题。我只需要在Activity
中创建后获得布局RelativeLayout shareLayout = (RelativeLayout) getActivity().findViewById(R.id.loveSpace);
shareLayout.setDrawingCacheEnabled(true);
shareLayout.buildDrawingCache();
Bitmap bm = shareLayout.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
答案 1 :(得分:0)
RelativeLayout rlMain = (RelativeLayout)findViewById(R.id.abc);
rlMain.setDrawingCacheEnabled(true);
Bitmap bitmap = rlMain.getDrawingCache();
String file = getFilename();
try {
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
rlMain.invalidate();
} catch (Exception e) {
e.printStackTrace();
} finally {
rlMain.setDrawingCacheEnabled(false);
}
private String getFilename() {
File file = new File(IMAGE_PATH);
if (!file.exists()) {
file.mkdirs();
}
String uriSting = (file.getAbsolutePath() + "/"
+ System.currentTimeMillis() + ".jpg");
return uriSting;
}