我有这个代码用于获取当前视图的屏幕截图,这是一个存在于活动中的片段,其中活动只有背景。
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;
}
但保存的位图并不是我所期待的。 屏幕截图仅包含片段元素,但不包含活动背景。如何将其包含在屏幕截图中?
答案 0 :(得分:0)
来自:How to programmatically take a screenshot in 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();
}
试试这个。它对我有用。对你而言
答案 1 :(得分: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;
}
我在一些不同的应用程序中使用了一段时间并且没有任何问题。希望它有助于