Android 合併生成分享圖片(View截圖)
阿新 • • 發佈:2019-02-16
有時候分享功能都是很需要分享一個當前螢幕的介面的截圖因,以前做校內APP的時候用到過,拿出來分享分享,
用以前以前寫過的自定義課表軟體 ,
原生View截圖 | 合成分享的圖片 |
|
|
看到的是圖片只顯示到11節處,下面的沒有顯示到 所以用到的 ScrollView
因此截圖節擷取ScrollView View的圖片
一,首先計算出整個ScrollView 的高度寬度生成對應大小的的Bitmap 然後把使用Canvas 將ScrollView 的介面繪製上去
// 獲取ScrollView 實際高度
h = 0 ;
for (int i = 0; i < scrollView.getChildCount(); i++) {
h += scrollView.getChildAt(i).getHeight();
scrollView.getChildAt(i).setBackgroundResource(android.R.color.white);
}
// 建立對應大小的bitmap
Bitmap bitmap = Bitmap.createBitmap(scrollView.getWidth (), h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
scrollView.draw(canvas);
二、獲取分享的頭部和底部圖片的Bitmap
// BitmapFactory.decodeResource函式直接轉換資原始檔為Bitmap
Bitmap head = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.share_term_table_header);
Bitmap foot = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.share_term_table_footer);
三、合併頭部底部和介面View的截圖
if (head == null) {
return null;
}
int headWidth = head.getWidth();
int kebianwidth = kebiao.getWidth();
int fotwid = san.getWidth();
int headHeight = head.getHeight();
int kebiaoheight = kebiao.getHeight();
int footerheight = san.getHeight();
//生成三個圖片合併大小的Bitmap
Bitmap newbmp = Bitmap.createBitmap(kebianwidth, headHeight + kebiaoheight + footerheight, Bitmap.Config.ARGB_8888);
Canvas cv = new Canvas(newbmp);
cv.drawBitmap(head, 0, 0, null);// 在 0,0座標開始畫入headBitmap
//因為手機不同圖片的大小的可能小了 就繪製白色的介面填充剩下的介面
if (headWidth < kebianwidth) {
System.out.println("繪製頭");
Bitmap ne = Bitmap.createBitmap(kebianwidth - headWidth, headHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(ne);
canvas.drawColor(Color.WHITE);
cv.drawBitmap(ne, headWidth, 0, null);
}
cv.drawBitmap(kebiao, 0, headHeight, null);// 在 0,headHeight座標開始填充課表的Bitmap
cv.drawBitmap(san, 0, headHeight + kebiaoheight, null);// 在 0,headHeight + kebiaoheight座標開始填充課表的Bitmap
//因為手機不同圖片的大小的可能小了 就繪製白色的介面填充剩下的介面
if (fotwid < kebianwidth) {
System.out.println("繪製");
Bitmap ne = Bitmap.createBitmap(kebianwidth - fotwid, footerheight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(ne);
canvas.drawColor(Color.WHITE);
cv.drawBitmap(ne, fotwid, headHeight + kebiaoheight, null);
}
cv.save(Canvas.ALL_SAVE_FLAG);// 儲存
cv.restore();// 儲存
//回收
head.recycle();
kebiao.recycle();
san.recycle();