Taking a screenshot of a particular view

suggest change

If you want to take a screenshot of a particular View v, then you can use the following code. v needs a non-zero size. The file uses getExternalStoragePublicDirectory, the pre-scoped-storage path. PNG ignores the quality argument 40.

Bitmap viewBitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
Canvas viewCanvas = new Canvas(viewBitmap);
Drawable backgroundDrawable = v.getBackground();

if (backgroundDrawable != null) {
    // Draw the background onto the canvas.
    backgroundDrawable.setBounds(0, 0, v.getWidth(), v.getHeight());
    backgroundDrawable.draw(viewCanvas);
} else {
    viewCanvas.drawColor(Color.GREEN);
}
// Draw the view onto the canvas.
v.draw(viewCanvas);

// Write the bitmap generated above into a file.
String fileStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
OutputStream outputStream = null;
try{
    File imgFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileStamp + ".png");
    outputStream = new FileOutputStream(imgFile);
    viewBitmap.compress(Bitmap.CompressFormat.PNG, 40, outputStream);
    outputStream.close();
}
catch(Exception e){
    e.printStackTrace();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents