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

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

本文介绍了在Android屏幕外将视图渲染为位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将视图渲染为位图并保存位图.但是我需要在屏幕外完成所有操作.

I Want to render a view to a Bitmap and save the bitmap.But i need to do that all in off screen.

我已经尝试过了:

    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();
    }

我的应用程序崩溃,因为视图没有任何宽度或高度.(该措施是为了解决该问题)

My app crash because the view doesnt have any width or height. ( the measure is a try to fix that )

抱歉英语不好.

推荐答案

问题在这里:

linearview = inflater.inflate(R.layout.intro, null);

您需要传递父级布局,以便可以对其进行正确测量.我了解您不希望将视图附加到布局,但是您可以通过使用此方法的此版本来将父布局仅用于测量,将false传递给attachToRoot.

You need to pass a parent layout, so it can be properly measured.I understand you do not want the view to be attached to the layout, but you can use a parent layout just for the measuring by using this other version of the method, passing false to attachToRoot.

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

从参数说明者的官方文档中获得

From the official documentation of the paramenters:

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

attachToRoot : Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

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

When in doubt you can always pass the app content as a parent layout:

findViewById(android.R.id.content);

这篇关于在Android屏幕外将视图渲染为位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:50