Search code examples
javaandroidandroid-layoutscreen-capture

Capture ViewGroup into an Image File


I have a simple combination of one ImageView and two TextViews over it. I would like to make the TextViews overlap the ImageView, and then save the combination as a whole (as PNG for example).

I know I can layer the TextViews over the ImageView using a FrameLayout, which I am already doing. Now what I am wondering is, how can I export that to an image?

I read various posts about using a Canvas. Is there a way to just export the FrameLayout as a PNG image, say, or do I need to create a canvas, add the ImageView and TextViews, and export the canvas itself as a PNG?

Thank you in advance.


Solution

  • Can it be done easily?, YES

    How?

    Well, I happen to have made a function for this the other day and it's really straightforward (make sure you have the write to external device permission). All you do is specify which view (it will include all the children views too) you want to "paint" to a Bitmap and afterwards you can either save it as a file like you say, or use it somewhere in you app.

    public void captureView(int viewId,String filename){
        //Find the view we are after
        View    view = (View) findViewById(viewId);
        //Create a Bitmap with the same dimensions 
        Bitmap image = Bitmap.createBitmap(view.getWidth(), 
                                           view.getHeight(), 
                                           Bitmap.Config.RGB_565);
        //Draw the view inside the Bitmap
        view.draw(new Canvas(image)); 
    
        //Store to sdcard
        try {
           String path = Environment.getExternalStorageDirectory().toString();
           File myFile = new File(path,filename);
           FileOutputStream out = new FileOutputStream(myFile);
    
           image.compress(Bitmap.CompressFormat.PNG, 90, out); //Output
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
    

    Notes Avoid trying to execute this code on the onCreate method since you're likely to be trying to fetch the width and height of the view prior to it being drawn and therefor will result in an error since the dimensions of the Bitmap can not be 0.

    Does it capture the view as it is or as it was created?

    I wasn't really sure at first but after a little testing, it appears that what you see is what you get, so if you have something rotating or different from the original disposition on launch it will reflect this in the capture. This may or may not be what you're after but it's what it provides. Here's an example of a LinearLayout captured (no screenshot or crop, just direct from the device).

    view capture