我想将视图渲染为位图并保存位图。但是我需要在屏幕外进行所有操作。
我已经试过了:
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:是否应将膨胀的层次结构附加到root参数?如果为false,则root仅用于为XML中的根视图创建LayoutParams的正确子类。
如有疑问,您可以始终将应用程序内容作为父布局传递:
findViewById(android.R.id.content);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句