Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getDrawingCache() returns null

Tags:

android

bitmap

I'm working on a simple painting app and trying to implement the functionality of giving more space to draw when a user requests, which I thought could be done by simply enabling scrolling of my CustomView class(which is contained in a LinearLayout then in a ScrollView class). If I didn't resize the CustomView class by running Chunk 1, Chunk 2 works fine(It simply saves one screen of drawing. At this time, there is no scrolling.) A bummer! Chunk 2 fails(view.getDrawingCache() returns null) when Chunk 1 is run (At this time, scrolling is enabled). I want to save the entire view including the part left out due to scrolling.

Chunk 1:

CustomView view = (CustomView) findViewById(R.id.customViewId);
height = 2 * height;
view.setLayoutParams(new LinearLayout.LayoutParams(width, height));

Chunk 2:

CustomView view = (CustomView) findViewById(R.id.customViewId);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);

These two chunks of codes are independent and small parts in two different methods.

Edited: SOLVED

After billions of Google queries, the problem is now SOLVED ;)
I referred to this thread, https://groups.google.com/forum/?fromgroups=#!topic/android-developers/VQM5WmxPilM.
What I didn't understand was getDrawingCache() method has the limit on the View class's size(width and height). If the View class is too big, getDrawingCache() simply returns null.
So, the solution was not to use the method and instead do it like below.

CustomView view = (CustomView) findViewById(R.id.customViewId);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), 
  view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 
Canvas bitmapHolder = new Canvas(bitmap); 
view.draw(bitmapHolder);
// bitmap now contains the data we need! Do whatever with it!
like image 921
user1831301 Avatar asked Dec 10 '12 11:12

user1831301


1 Answers

You need to call buildDrawingCache(), before being able to use the bitmap.

The setDrawingCache(true) thing just sets the flag and waits for the next drawing pass in order to create the cache bitmap.

Also don't forget to call destroyDrawingCache() when you no longer need it.

like image 177
asenovm Avatar answered Sep 28 '22 05:09

asenovm