Bobbake4
Bobbake4

Reputation: 24857

Android get a bitmap of a view before drawing?

I am looking to take a view hierarchy and turn it into a Bitmap. Using the view.getDrawingCache() does exactly what I want it to do but will not work if I try that before the view is drawn. Is there another function that will do the same thing but before it is actually drawn? I would like to create the view and turn it into a bitmap to display and discard the actual view. If there is a way to force the view to be drawn that might work as well. Any ideas?

I found this in a previous post:

    public static Bitmap loadBitmapFromView(View v) {
         Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
         Canvas c = new Canvas(b);
         v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
         v.draw(c);
         return b;
    }

This looks promising but when I use it all I get is a semi transparent black box.

Upvotes: 3

Views: 2315

Answers (1)

Bobbake4
Bobbake4

Reputation: 24857

Alright I figured it out. You can use this code, slightly modified from this post.

    public static Bitmap loadBitmapFromView(View v) {
          Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
          Canvas c = new Canvas(b);
          v.measure(v.getLayoutParams().width, v.getLayoutParams().height); //Change from original post
          v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
          v.draw(c);
          return b;
    }

Upvotes: 3

Related Questions