如何以编程方式截取屏幕截图并将其保存在图库中?

时间:2013-03-07 16:23:16

标签: android sdk

我想知道当前屏幕的屏幕截图(按下按钮后)的代码是什么,并将其保存在图库中,因为我没有带SD卡的设备。所以我想保存在默认的库中。谢谢

4 个答案:

答案 0 :(得分:10)

  Bitmap bitmap;
  View v1 = findViewById(R.id.rlid);// get ur root view id
  v1.setDrawingCacheEnabled(true); 
  bitmap = Bitmap.createBitmap(v1.getDrawingCache());
  v1.setDrawingCacheEnabled(false);

这应该可以解决问题。

保存

  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
  File f = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "test.jpg")
  f.createNewFile();
  FileOutputStream fo = new FileOutputStream(f);
  fo.write(bytes.toByteArray()); 
  fo.close();

答案 1 :(得分:5)

    View v1 = L1.getRootView();
    v1.setDrawingCacheEnabled(true);
    Bitmap bm = v1.getDrawingCache();
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
    image = (ImageView) findViewById(R.id.screenshots);
    image.setBackgroundDrawable(bitmapDrawable);

有关完整的源代码,请浏览以下博客

http://amitandroid.blogspot.in/2013/02/android-taking-screen-shots-through-code.html

用于存储位图以查看以下链接

Android Saving created bitmap to directory on sd card

答案 2 :(得分:1)

这将保存到图库。该代码还设置了一个图像路径..这对Intent.SEND_ACTION和电子邮件Intents很有用。

String imagePath = null;
Bitmap imageBitmap = screenShot(mAnyView);
if (imageBitmap != null) {
    imagePath = MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, "title", null);
}


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

答案 3 :(得分:0)

正如323go所述,除非你的设备是真的,否则这是不可能的。

但如果是的话,monkeyrunner或者你使用模拟器可能会很好。

相关问题