Getting bitmap from a view (visible, invisible, onCreate)

There are a couple of ways to obtain a bitmap image from a visible view object. However, its a bit more tricky to obtain the bitmap from invisible (or hidden) views.

1. Obtaining bitmaps from visible views

The first approach would be to use the drawing cache of the view class (recommended). Note that while v.getDrawingCache() would provide the actual bitmap representation, it is necessary to create an immutable clone of this referenced object. Otherwise, the bitmap would be lost when the cache is cleared.

The second approach would be to expose the createSnapshot() method available in the view class itself. Doing so would change the android api and require some framework changes. Here, the @hide comment would be useful to avoid updates to the api-methods in the actual build itself.

However, these methods normally would not work for invisible or hidden views. The bitmaps would be 0kb or null.

2. Bitmaps from invisible (hidden) view / or within Activity.onCreate()

How do you get a view that is invisible? The problem lies with the fact that the width and height properties of hidden views = 0. You need to utilize a measurement feature of the view.

Alternatively, if you are only trying to get a snapshot of the screen, it would be easy to use the getDisplay().width() and height() as proxies for the actual size of the view .

  8 comments for “Getting bitmap from a view (visible, invisible, onCreate)

  1. Harry
    November 9, 2011 at 5:45 am

    Thx a lot! Perfect!

  2. Eitan
    July 25, 2012 at 5:44 am

    Thx mate, very helpful 🙂

  3. VAdaihiep
    June 13, 2013 at 3:08 am

    Thanks in advance, very useful.

  4. Mursaleen
    May 13, 2014 at 6:47 pm

    In my case, v.getDrawingCache() returns null

  5. Anujdeo
    February 3, 2016 at 9:55 pm

    Thanks a lot! You saved my day 🙂 Method 1 works perfect!
    God Bless You…

  6. Denis
    March 9, 2016 at 10:51 pm

    Thanks a lot! Wery helpful!

  7. Denis
    March 9, 2016 at 10:52 pm

    Very helpful! Thanks a lot!

  8. Krisztián
    May 26, 2016 at 5:27 pm

    I am trying to draw a RelativeLayout to a bitmap. Your method is working perfectly but I have to mention this: If I use a TextView/AppcompatTextView with drawableStart/End it is not showing altough drawableLeft/Right are visible. However the result is the same with this:
    Bitmap bitmap = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Config.ARGB_8888);
    Canvas c = new Canvas(bitmap);
    return bitmap;

Leave a Reply

Your email address will not be published. Required fields are marked *