[英]Render View to Bitmap off-screen in Android
我想渲染一个Bitmap视图并保存位图。 但我需要在屏幕外完成所有操作。
我试过这个:
LayoutInflater inflater = getLayoutInflater();
View linearview = (View) findViewById(R.id.linearview);
linearview = inflater.inflate(R.layout.intro, null);
Bitmap bm = Bitmap.createBitmap( linearview.getMeasuredWidth(), linearview.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
linearview.layout(0, 0, linearview.getLayoutParams().width, linearview.getLayoutParams().height);
linearview.draw(c);
String extStorageDirectory = Environment.getExternalStorageState().toString();
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "screen1.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
编辑:我的应用程序崩溃,因为视图没有任何宽度或高度。 (该措施试图解决这个问题)
并为不好的英语而苦恼。
问题出在这里:
linearview = inflater.inflate(R.layout.intro, null);
您需要传递父布局,以便可以正确测量。 我知道您不希望视图附加到布局,但您可以使用父布局仅用于测量,方法是使用此方法的其他版本,将false传递给attachToRoot。
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
从参数的官方文档:
root :可选视图是生成的层次结构的父级(如果attachToRoot为true),或者只是一个为返回的层次结构的根提供一组LayoutParams值的对象(如果attachToRoot为false)。
attachToRoot :膨胀的层次结构是否应附加到根参数? 如果为false,则root仅用于为XML中的根视图创建LayoutParams的正确子类。
如有疑问,您可以随时将应用内容作为父布局传递:
findViewById(android.R.id.content);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.