我的应用程序在相对布局中有一个列表视图。现在我需要拍摄整个布局的屏幕截图,包括列表视图中可用的所有内容以及布局中显示的按钮和文本视图等其他内容。但我的代码只占用屏幕的可见部分。这里的视图是父布局。
public void screen(){
View v1 = findViewById(R.id.screenRoot);
rel.layout(0, 0, rel.getMeasuredWidth(),rel.getMeasuredHeight());
View v = v1.getRootView();
v.setDrawingCacheEnabled(true);
/* v.measure(MeasureSpec.makeMeasureSpec(w, w),
MeasureSpec.makeMeasureSpec(h, h));*/
// v.layout(0, 0, rel.getWidth(), rel.getHeight());
v.buildDrawingCache(true);
System.out.println("rel "+rel.getHeight()+" "+v.getHeight());
Bitmap b = v.getDrawingCache();
v.setDrawingCacheEnabled(false);
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "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");
System.out.println("my path "+myPath+" "+fos);
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Image Captured Successfully", 0).show();
}
答案 0 :(得分:1)
从Click事件或任何事物中调用getBitmapFromView。 R.id.root是我的主要RelativeLayout所以你可以传递给你主要的布局。
LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout root = (RelativeLayout)inflater.inflate(R.layout.youlayourfile,null);
root.setDrawingCacheEnabled(true);
Bitmap bmp = getBitmapFromView(this.getWindow().getDecorView().findViewById(R.id.root).getRootView());
URI uri = storPrintFile(bmp);
此函数返回布局的位图。现在,您只需将位图存储到您的设备和其他任何位置。
public Bitmap getBitmapFromView(View v) {
v.setLayoutParams(new LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.RGB_565);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
将位图存储到设备中。
public URI storPrintFile(Bitmap bitmapToStore){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
String path = cw.getDir("CapturedImages",Context.MODE_PRIVATE).getPath();
File file = new File(path);
boolean isFileCreated = false;
if (!file.exists()) {
isFileCreated = file.mkdir();
System.out.println("Directory created in Internal Storage is :" + path);
}
String current = "Screen.jpg";//uniqueId.replace(" ", "-").replace(":", "-") + ".jpeg";
System.out.println("Internal Storage path is : " + current);
File mypath = new File(file, current);
try {
FileOutputStream out = new FileOutputStream(mypath);
bitmapToStore.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath.toURI();
}