在 Android 中在屏幕外将视图渲染为位图

Eva*_*ira 5 java android

我想将视图渲染到位图并保存位图。但我需要在屏幕外完成这一切。

我试过这个:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

编辑:我的应用程序崩溃,因为视图没有任何宽度或高度。(措施是试图解决这个问题)

并为糟糕的英语道歉。

sha*_*afi 2

问题就在这里:

linearview = inflater.inflate(R.layout.intro, null);
Run Code Online (Sandbox Code Playgroud)

您需要传递父布局,以便可以正确测量它。我知道您不希望将视图附加到布局,但您可以通过使用该方法的其他版本,将 false 传递给 AttachToRoot,仅使用父布局进行测量。

public View inflate (int resource, ViewGroup root, boolean attachToRoot)
Run Code Online (Sandbox Code Playgroud)

来自参数的官方文档:

root:可选视图作为生成的层次结构的父级(如果 AttachToRoot 为 true),或者只是一个为返回的层次结构的根提供一组 LayoutParams 值的对象(如果 AttachToRoot 为 false。)

AttachToRoot:膨胀的层次结构是否应附加到根参数?如果为 false,则 root 仅用于为 XML 中的根视图创建正确的 LayoutParams 子类。

如有疑问,您始终可以将应用程序内容作为父布局传递:

findViewById(android.R.id.content);
Run Code Online (Sandbox Code Playgroud)