Android : taking Screenshot of the selected area p

2019-05-29 02:18发布

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.

2条回答
做自己的国王
2楼-- · 2019-05-29 02:35

Below method takes snapshot of given view which is adjustable by means of height and width then returns bitmap of it

public static Bitmap takeSnapshot(View givenView, int width, int height) {
Bitmap bm = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);                
Canvas snap = new Canvas(bm);
givenView.layout(0, 0, givenView.getLayoutParams().width, givenView.getLayoutParams().height);
givenView.draw(snap);
return bm;  }
查看更多
祖国的老花朵
3楼-- · 2019-05-29 02:48

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);
查看更多
登录 后发表回答