当我以编程方式触发屏幕截图时,“相机预览”会在保存的屏幕截图上消失

时间:2019-07-01 13:20:18

标签: android android-camera2

我制作了一个应用程序,该应用程序根据图像分类检查某些东西是否正确或错误。分类后,它会触发屏幕截图。所有的UI元素都在屏幕截图上,但是我需要的实际图像被忽略了。

当我手动制作屏幕截图时,没有任何遗漏。

那么我该如何更改代码以使我的应用程序执行正常的屏幕截图?

我的启动活动:

/** Main {@code Activity} class for the Camera app. */
public class CameraActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
    }

    public void startCamera(View view){
            setContentView(R.layout.activity_inspection);
            getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.container2, Camera2BasicFragment.newInstance())
                    .commit();
    }

}

检查活动:

public class Inspection extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_inspection);
}

}

以及 Camera2BasicFragment 类中使用的 takeScreenshot ()方法:

    private void takeScreenshot() {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

    try {
      // image naming and path  to include sd card  appending name you choose for file
      String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

      // create bitmap screen capture
      View v1 = getActivity().getWindow().getDecorView();
      v1.setDrawingCacheEnabled(true);
      Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
      v1.setDrawingCacheEnabled(false);

      File imageFile = new File(mPath);

      FileOutputStream outputStream = new FileOutputStream(imageFile);
      int quality = 100;
      bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
      outputStream.flush();
      outputStream.close();

      //openScreenshot(imageFile);
    } catch (Throwable e) {
      // Several error may come out with file handling or DOM
      e.printStackTrace();
    }
  }

1 个答案:

答案 0 :(得分:0)

使用以下代码对所需的视图进行截图,

private void captureScreen() {
  View v =  this.getWindow().getDecorView().findViewById(android.R.id.content);
  v.setDrawingCacheEnabled(true);
  Bitmap bitmap = v.getDrawingCache();
  String extr = Environment.getExternalStorageDirectory().toString();
  File file = new File(extr, "fff" + ".jpg");
  FileOutputStream f = null;
      try {
      f = new FileOutputStream(file);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, f);
      f.flush();
      f.close();
      MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
}