我基本上尝试在我的Activity中捕获相对布局的屏幕截图并将其另存为PNG图像。然后我需要将其检索为Bitmap文件。我写了一些代码来完成这项工作但遗憾的是屏幕截图没有保存在我的设备上。
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Other views -->
</RelativeLayout>
代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_view);
//The view that needs to be captured as an image
parent = (RelativeLayout) findViewById(R.id.parent);
Bitmap image = getBitmapFromView(parent);
}
public static Bitmap getBitmapFromView(View view) {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
Bitmap returnBitmap = null;
try {
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
//Retrieve the image as a Bitmap and return it
if(imageFile.exists()){
returnBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
}
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
return returnBitmap;
}
上述代码不起作用。没有错误,但未捕获并保存视图。有人可以指出问题或者给我一个更好的解决方案吗?
答案 0 :(得分:1)
首先为相关视图指定一个ID
使用findViewById()
获取参考
然后按照此代码段
//定义具有视图高度和宽度的位图
Bitmap viewBitmap = Bitmap.createBitmap(v.getWidth(),v.getHeight(),Bitmap.Config.RGB_565);
Canvas viewCanvas = new Canvas(viewBitmap);
//get background of canvas
Drawable backgroundDrawable = v.getBackground();
if(backgroundDrawable!=null){
backgroundDrawable.draw(viewCanvas);//draw the background on canvas;
}
else{
viewCanvas.drawColor(Color.GREEN);
//draw on canvas
v.draw(viewCanvas)
}
//write the above generated bitmap to a file
String fileStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
OutputStream outputStream = null;
try{
imgFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),fileStamp+".png");
outputStream = new FileOutputStream(imgFile);
b.compress(Bitmap.CompressFormat.PNG,40,outputStream);
outputStream.close();
}
catch(Exception e){
e.printStackTrace();
}
用JPEG替换PNG
不要忘记添加此权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
希望这会有所帮助:)