Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android View.getDrawingCache returns null, only null

Would anyone please try to explain to me why

public void addView(View child) {   child.setDrawingCacheEnabled(true);   child.setWillNotCacheDrawing(false);   child.setWillNotDraw(false);   child.buildDrawingCache();   if(child.getDrawingCache() == null) { //TODO Make this work!     Log.w("View", "View child's drawing cache is null");   }   setImageBitmap(child.getDrawingCache()); //TODO MAKE THIS WORK!!! } 

ALWAYS logs that the drawing cache is null, and sets the bitmap to null?

Do I have to actually draw the view before the cache is set?

Thanks!

like image 365
Bex Avatar asked Feb 26 '10 04:02

Bex


2 Answers

I was having this problem also and found this answer:

v.setDrawingCacheEnabled(true);  // this is the important code :)   // Without it the view will have a dimension of 0,0 and the bitmap will be null           v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),              MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());   v.buildDrawingCache(true); Bitmap b = Bitmap.createBitmap(v.getDrawingCache()); v.setDrawingCacheEnabled(false); // clear drawing cache 
like image 176
Marcio Covre Avatar answered Sep 17 '22 10:09

Marcio Covre


if getDrawingCache is always returning null guys: use this:

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

Reference: https://stackoverflow.com/a/6272951/371749

like image 38
cV2 Avatar answered Sep 20 '22 10:09

cV2