getDrawingCache() returns null

别来无恙 提交于 2020-01-21 04:45:49

问题


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!

回答1:


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.



来源:https://stackoverflow.com/questions/13799917/getdrawingcache-returns-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!