如何在android中截取布局的截图

Adi*_*ark 3 android android-gallery android-layout android-studio

我想通过拍摄布局的屏幕截图将我的框架布局保存到图库中.这段代码适用于一个项目(名称:试用版),但当我在其他项目(名称:Fg)上尝试相同的代码时,它无效.照片未保存在图库中.

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




}
public Bitmap click(View view) {
    FrameLayout memecontentView =(FrameLayout) findViewById(R.id.my);
    View view1 = memecontentView;

    Bitmap b = Bitmap.createBitmap(view1.getWidth(), view1.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(b);
    view1.draw(canvas);


    String extr = Environment.getExternalStorageDirectory().toString();
    File myPath = new File(extr, getString(R.string.free_tiket)+".jpg");
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(myPath);
        b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        MediaStore.Images.Media.insertImage(getContentResolver(), b,
                "Screen", "screen");

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


}
Run Code Online (Sandbox Code Playgroud)

}

Koa*_*ied 5

你有没有

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

在你的清单中声明?

此外,如果你想要整个视图试试这个:

view1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view1.getDrawingCache());
Run Code Online (Sandbox Code Playgroud)

哦,这可能会节省你一些时间:

private void openScreenshot(File imageFile) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(imageFile);
    intent.setDataAndType(uri, "image/*");
    startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)

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