Android:如何通过编程方式对所选区域进行屏幕截图

3

我的代码如下:

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();
    }
}  

这段代码可以截取全屏,但我想在按下按钮后以编程方式截取特定区域(例如屏幕左侧块)的截图。欢迎提供任何代码或建议。

2个回答

4
你可以将内容放在布局中,例如LinearLayout,并使用包装布局上的方法按照上面的代码来截取屏幕截图。
 Bitmap bitmap;
 ViewGroup v1 = findViewById(R.id.layout_id);
 v1.setDrawingCacheEnabled(true);
 bitmap = Bitmap.createBitmap(v1.getDrawingCache());
 v1.setDrawingCacheEnabled(false);

谢谢!这对我很有用。 - hiein2003

1
下面的方法可以对给定的视图进行快照,可通过高度和宽度进行调整,然后返回其位图。
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;  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接