开发者

Android get a bitmap of a view before drawing?

开发者 https://www.devze.com 2023-04-13 06:53 出处:网络
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 a

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) {
       开发者_Go百科  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.


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;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号