文章連接: https://mp.weixin.qq.com/s/FQmYfT-KYiDbp-0HzK_Hpw
項目中常常會用到分享的功能,有分享連接也有分享圖片,其中分享圖片有的須要移動端對屏幕內容進行截取分享,說白了就是將view 轉成bitmap 再到圖片分享,還有一種狀況是將不可見的view 轉成bitmap ,這種view是沒有直接顯示在界面上的,須要咱們使用inflate 進行建立的view。git
先看經過 DrawingCache 方法來截取普通的view,獲取它的視圖(Bitmap)。github
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());
另外寫了個簡易的保存圖片的方法,方便查看效果的。ui
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/view2bitmapthis
歡迎關注個人博客:https://www.manjiexiang.cn/ spa
更多精彩歡迎關注微信號:春風十里不如認識你
一塊兒學習 一塊兒進步code