Android:以编程方式截取所选区域的屏幕截图

时间:2014-10-04 07:56:43

标签: android screenshot

我的代码如下:

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 个答案:

答案 0 :(得分:3)

您可以将内容包装在布局中,例如LinearLayout,并按照上面的代码使用包装布局上的方法进行截屏。

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

答案 1 :(得分:0)

下面的方法获取给定视图的快照,该视图可通过高度和宽度调整,然后返回它的位图

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