In Android the screen capture implementation method of the current Activity is obtained by view

  • 2020-06-12 10:34:15
  • OfStack

This method USES view to get screen shots of the current activity, not framebuffer, so it has a certain limitation. But this approach is relatively simple and easy to understand.

First get the screen capture in Bitmap format with the following function:


public Bitmap myShot(Activity activity) {
// To obtain windows At the top of the pyramid view
View view = activity.getWindow().getDecorView();
view.buildDrawingCache();
// Gets the status bar height
Rect rect = new Rect();
view.getWindowVisibleDisplayFrame(rect);
int statusBarHeights = rect.top;
Display display = activity.getWindowManager().getDefaultDisplay();
// Gets the screen width and height
int widths = display.getWidth();
int heights = display.getHeight();
// Allows the current window to hold cache information
view.setDrawingCacheEnabled(true);
// Remove the status bar
Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
statusBarHeights, widths, heights � statusBarHeights);
// Destroy cache information
view.destroyDrawingCache();
return bmp;
}

Once you have an image in bitmap format, you can either save it to an sd card or display it directly to ImageView as follows:


// will bitmap Converted to drawable
BitmapDrawable bd=new BitmapDrawable(myShot());
imageView.setBackgroundDrawable(bd);
imageView.setImageBitmap(myShot());

If you want to write to sd to save, you can use the following method:


private void saveToSD(Bitmap bmp, String dirName,String fileName) throws IOException {
// judge sd Whether the card exists
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File dir = new File(dirName);
// Determines whether a folder exists or not
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dirName + fileName);
// Determines whether the file exists or not, or creates it
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
// The first 1 The parameter is the image format, number 2 One is picture quality, no 3 One is the output stream
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
// Use up close
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

dirName as output folder name, filaName is the output file name, both of the path of the output, such as "/ mnt/sdcard/pictures/shot png". Also note that register write permissions with AndroidManifest:


<uses-permission android:name= " android.permission.WRITE_EXTERNAL_STORAGE " />


Related articles: