Would anyone please try to explain to me why
public void addView(View child) {
child.setDrawingCacheEnabled(true);
child.setWillNotCacheDrawing(false);
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
Work best 4me
Bitmap bitmap = Bitmap.createBitmap( screen.getMeasuredWidth(), screen.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
screen.layout(0, 0, screen.getMeasuredWidth(), screen.getMeasuredHeight());
screen.draw(canvas);
If the view you want catch really shows on screen, but it return null. That means you catch the view before Window manager generate it. Some layouts are very complicated. If layout includes nested layouts, layout_weight..etc, it causes several times relayout to get exactly size. The best solution is waiting until window manager finish job and then get screen shot. Try to put getDrawingCache() in handler.
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
The error may be bacause your View too large to fit into drawing cache.
I got the explanation of my "View.getDrawingCache returns null" problem from my logs:
W/View: View too large to fit into drawing cache, needs 19324704 bytes, only 16384000 available
Android docs also says: Android devices can have as little as 16MB of memory available to a single application. That is why you can not load big bitmap.
This the simple and efficient way to get bitmap
public void addView(View v) {
v.setDrawingCacheEnabled(true);
v.buildDrawingCache();
Bitmap bitmap = v.getDrawingCache();
if(bitmap == null) {
// bitmap is null
// do whatever you want
} else {
setImageBitmap(bitmap);
}
v.setDrawingCacheEnabled(false);
v.destroyDrawingCache();
}