android-以编程方式截取特定视图的屏幕截图不起作用

时间:2016-11-14 09:20:48

标签: android android-studio android-sdk-2.3

我想从另一个活动中截取布局的屏幕截图。当我查看Bitmap时,它显示NullPointerExcenption。这是我的代码

  View v=LayoutInflater.from(this).inflate(R.layout.score_share, null);
    layoutScore.setDrawingCacheEnabled(true);
    Bitmap bm= Bitmap.createBitmap(v.getDrawingCache());
    layoutScore.setDrawingCacheEnabled(false);
    File file= new File(Environment.getExternalStorageDirectory()+"/scs.jpg");
    try {
        FileOutputStream outputStream= new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG,100, outputStream);
        outputStream.flush();
        outputStream.close();

        openScreenshot(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:1)

以下是捕获屏幕截图的方法。

 public Bitmap getScreenShot(View view) {
       View screenView = view.getRootView();
       screenView.setDrawingCacheEnabled(true);
       Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
       screenView.setDrawingCacheEnabled(false);
       return bitmap;
 }

将位图存储到SD卡中:

public void store(Bitmap bm, String fileName){
    final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
    File dir = new File(dirPath);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

现在为布局和捕获屏幕截图充气

View view=LayoutInflater.from(this).inflate(R.layout.score_share, null);

Bitmap bmp = getScreenShot(view);

bmp是必需的屏幕截图,然后将其保存到SD卡,如

store(bmp, "Screenshot.jpg");

不要忘记在清单中添加写入外部存储权限

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

感谢您的回答enter image description here

答案 1 :(得分:0)

如果问题是getDrawingCache返回null,那么只需在v.buildDrawingCache(true);之前添加这行代码

v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
          MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 

这样可以防止视图的大小为(0,0),因此可以保证null为安全。