以编程方式对整个屏幕进行截图

3

我有一个代码用于截取当前视图的屏幕截图,这是一个嵌入到活动中的片段,在该活动中只有一个背景。

private File captureScreen() {

    Bitmap screenshot = null;
    try {

        if (view != null) {

            screenshot = Bitmap.createBitmap(view.getMeasuredWidth(),
                    view.getMeasuredHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(screenshot);
            view.draw(canvas);
            // save pics
            File cache_dir = Environment.getExternalStorageDirectory();
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            screenshot.compress(Bitmap.CompressFormat.PNG, 90, bytes);
            File f = new File(cache_dir + File.separator + "screen.png");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            fo.close();
            return f;
        }
    } catch (Exception e) {
        // TODO
    }
    return null;
}

但保存的位图不是我预期的那样。截图仅包含部分元素,而非活动背景。如何将其包含在截图中?


1
我建议您从这个问题中寻求帮助。 https://dev59.com/3nE85IYBdhLWcg3wr1ge - Umair Khalid
2个回答

0

来源:如何在Android中以编程方式截取屏幕截图?

// image naming and path  to include sd card  appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;   
// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

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

try {
  fout = new FileOutputStream(imageFile);
  bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
  fout.flush();
  fout.close();

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

试试这个。对我有效,对你也一样。


0

调用此方法,传入您想要屏幕截图的最外层ViewGroup:

public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
            view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

我在几个不同的应用程序中使用了一段时间,没有遇到任何问题。希望它能有所帮助。


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