Search code examples
androidscreenshot

Android : taking Screenshot of the selected area programmatically


My code is as follow :

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button upload = (Button) findViewById(R.id.screeshotdButton);

    upload.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            folderCheck();
        }
    });
}
private void folderCheck(){
    File folder = new File(Environment.getExternalStorageDirectory() + "/cloze_screenshots");
    boolean success = true;
    // If the folder cloze not exist, create one
    if (!folder.exists()) {
        success = folder.mkdir();       
    }else{
        ScreenShot();
    }
    // If mkdir successful
    if (success) {
        ScreenShot();       
    } else {
        Log.e("mkdir_fail","QQ"); 
    }

}

private void ScreenShot(){

    String filePath = Environment.getExternalStorageDirectory()+ "/cloze_screenshots/temp.png"; 

    // create bitmap screen capture
    Bitmap bitmap;
    View v1 = getWindow().getDecorView().getRootView();
    v1.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);

    OutputStream fout = null;
    File imageFile = new File(filePath);

    try {
        fout = new FileOutputStream(imageFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
        fout.flush();
        fout.close();
        Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}  

This code can take a fullscreen screenshot , but I want to take a screenshot on specific area (For example, the left block on the screen ) programmatically after I press the button. Any code or suggestion will be appreciate.


Solution

  • You can wrap the contents in a layout for example LinearLayout and follow the above code for taking screenshot by using the methods on the wrapped layout.

     Bitmap bitmap;
     ViewGroup v1 = findViewById(R.id.layout_id);
     v1.setDrawingCacheEnabled(true);
     bitmap = Bitmap.createBitmap(v1.getDrawingCache());
     v1.setDrawingCacheEnabled(false);