Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render View to Bitmap off-screen in Android

Tags:

java

android

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

I've tried this:

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

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

And srry for the bad english.

like image 347
Evandro Barbosa Carreira Avatar asked Nov 04 '22 12:11

Evandro Barbosa Carreira


1 Answers

The problem is here:

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

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:

root : Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)

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);
like image 145
shalafi Avatar answered Nov 15 '22 06:11

shalafi