項目中經常會用到分享的功能,有分享鏈接也有分享圖片,其中分享圖片有的需要移動端對屏幕內容進行截取分享,說白了就是將view 轉成bitmap 再到圖片分享,還有一種情況是將不可見的view 轉成bitmap ,這種view是沒有直接顯示在界面上的,需要我們使用inflate 進行創建的view。
第一種
先看通過 DrawingCache 方法來截取普通的view,獲取它的視圖(Bitmap)。
private Bitmap createBitmap(View view) {
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
這個方法適用於view 已經顯示在界面上了,可以獲得view 的寬高實際大小,進而通過DrawingCache 保存為bitmap。
第二種
但是 如果要截取的view 沒有在屏幕上顯示完全的,例如要截取的是超過一屏的 scrollview ,通過上面這個方法是獲取不到bitmap的,需要使用下面方法,傳的view 是scrollview 的子view(LinearLayout)等, 當然完全顯示的view(第一種情況的view) 也可以使用這個方法截取。
public Bitmap createBitmap2(View v) {
Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
c.drawColor(Color.WHITE);
v.draw(c);
return bmp;
}
第三種
還有一種 是view完全沒有顯示在界面上,通過inflate 轉化的view,這時候通過 DrawingCache 是獲取不到bitmap 的,也拿不到view 的寬高,以上兩種方法都是不可行的。第三種方法通過measure、layout 去獲得view 的實際尺寸。
public Bitmap createBitmap3(View v, int width, int height) {
//測量使得view指定大小
int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
v.measure(measuredWidth, measuredHeight);
//調用layout方法布局后,可以得到view的尺寸大小
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
c.drawColor(Color.WHITE);
v.draw(c);
return bmp;
}
View view = LayoutInflater.from(this).inflate(R.layout.view_inflate, null, false);
//這里傳值屏幕寬高,得到的視圖即全屏大小
createBitmap3(view, getScreenWidth(), getScreenHeight());
另外寫了個簡易的保存圖片的方法,方便查看效果的。
private void saveBitmap(Bitmap bitmap) {
FileOutputStream fos;
try {
File root = Environment.getExternalStorageDirectory();
File file = new File(root, "test.png");
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
github地址:https://github.com/taixiang/view2bitmap
歡迎關注我的博客:https://www.manjiexiang.cn/
更多精彩歡迎關注微信號:春風十里不如認識你
一起學習 一起進步