I\'m trying to take a screenshot in code in Android. Actually the screenshot is the bitmap of the main RelativeLayout. The screenshot is taken but the content appears wrong, the
This works good for me:
View content = findViewById(R.id.myElementForScreenshoot);
View screenshot = content; // or content.getRootView() for fullscreen
screenshot.refreshDrawableState();
screenshot.setDrawingCacheEnabled(true);
Bitmap b = screenshot.getDrawingCache();
After this you can process or save bitmap. Hope it helped. Cheers
I'm assuming you're doing this during creation. Don't!
use a postDelayed(Runnable, int) to execute the Bitmap bm = Bitmap.createBitmap(v.getDrawingCache());
after the view is drawn.
also, remove the v.measure() and v.layout() those are methods for the ViewGroup to be calling.
Remove the lines:
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
//v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.layout(0, 0, v.getWidth(), v.getHeight());
I think you need to replace the
RelativeLayout v = (RelativeLayout)findViewById(R.id.main_layout);
v.setDrawingCacheEnabled(true);
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getWidth(), v.getHeight());
v.buildDrawingCache(true);
Bitmap bm = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
with
Bitmap bitmap;
View root = findViewById(android.R.id.content);
View v1 = root.getRootView();
v1.setDrawingCacheEnabled(true);
root.setDrawingCacheEnabled(true);
Bitmap bm = Bitmap.createBitmap(root.getDrawingCache());
root.setDrawingCacheEnabled(false);
Specify the screen size in makeMeasureSpec
...
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
v.measure(MeasureSpec.makeMeasureSpec(0, size.x),
MeasureSpec.makeMeasureSpec(0, size.y));
...
Also try setting the setDrawingCacheQuality to high, so that it returns a higher resolution bitmap.
LinearLayout ll = (LinearLayout )findViewById(R.id.layout);
ll .setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
Try this