国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android view轉Bitmap生成截圖的方法

2019-10-21 21:39:23
字體:
來源:轉載
供稿:網友

項目中經常會用到分享的功能,有分享鏈接也有分享圖片,其中分享圖片有的需要移動端對屏幕內容進行截取分享,說白了就是將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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 唐河县| 驻马店市| 将乐县| 汉阴县| 邹平县| 松桃| 兴城市| 旌德县| 西充县| 成安县| 本溪市| 南漳县| 敦煌市| 祁连县| 泽库县| 镇平县| 南投市| 屯昌县| 依兰县| 武安市| 资源县| 辽宁省| 长顺县| 涿州市| 孝感市| 蚌埠市| 清丰县| 巴林右旗| 咸宁市| 杨浦区| 化隆| 汉沽区| 清苑县| 韶山市| 中阳县| 卫辉市| 香格里拉县| 株洲县| 瓦房店市| 公安县| 宜宾县|