我一直在探索如何在Android中通过编程方式截屏,但是当进行截屏时,我只能够截取到工具栏和黑色屏幕,而没有真正呈现在屏幕上的内容。
我还尝试着截取我为谷歌地图创建的自定义信息窗口布局中的特定TextView。但是,下面第二行代码返回了一个空指针异常。
TextView v1 = (TextView)findViewById(R.id.tv_code);
v1.setDrawingCacheEnabled(true);
有没有办法在不安装Android截图库的情况下实际截取屏幕上的内容,或者截取自定义InfoWindow布局中的TextView?以下是我的截图方法:
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap 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");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
编辑:我已经改用源代码提供的方法。
如何在程序中同时截取Google地图v2和XML布局的屏幕截图并合并?
然而,它并没有截屏任何东西。
public void captureMapScreen() {
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
@Override
public void onSnapshotReady(Bitmap snapshot) {
try {
View mView = getWindow().getDecorView().getRootView();
mView.setDrawingCacheEnabled(true);
Bitmap backBitmap = mView.getDrawingCache();
Bitmap bmOverlay = Bitmap.createBitmap(
backBitmap.getWidth(), backBitmap.getHeight(),
backBitmap.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(backBitmap, 0, 0, null);
canvas.drawBitmap(snapshot, new Matrix(), null);
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/"
+ System.currentTimeMillis() + ".jpg");
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}