[英]Android: Taking screenshot of a View, Saving the image and retrieving it
我基本上試圖在我的活動中捕獲相對布局的屏幕截圖並將其保存為 PNG 圖像。 然后我需要將它作為位圖文件檢索。 我寫了一些代碼來完成這項工作,但遺憾的是屏幕截圖沒有保存在我的設備上。
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;
}
上面的代碼不起作用。 沒有錯誤,但未捕獲和保存視圖。 有人可以指出問題或給我一個更好的解決方案嗎?
首先為相關視圖分配一個id
使用findViewById()
獲取引用然后按照此代碼段進行操作
//定義一個帶有View的高度和寬度的位圖
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"/>
希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.