截圖的各種實現(全屏or長截圖)
阿新 • • 發佈:2019-01-06
全屏截圖:
/**
* 傳入的activity是要截圖的activity
*/
public static Bitmap getViewBitmap(Activity activity) {
// View是你需要截圖的View
View view = activity.getWindow().getDecorView();
//這兩句必須寫,否則getDrawingCache報空指標
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// 獲取狀態列高度
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
// 獲取螢幕長和高
int width = activity.getResources().getDisplayMetrics().widthPixels;
int height = activity.getResources().getDisplayMetrics().heightPixels;
// 去掉標題欄
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
ScrollView或者ListView或者LinearLayout等ViewGroup的長截圖:
public static Bitmap getViewGroupBitmap(ViewGroup viewGroup) {
//viewGroup的總高度
int h = 0;
Bitmap bitmap;
// 適用於ListView或RecyclerView等求高度
for (int i = 0; i < viewGroup.getChildCount(); i++) {
h += viewGroup.getChildAt(i).getHeight();
}
// 若viewGroup是ScrollView,那麼他的直接子元素有id的話,如下所示:
// h = mLinearLayout.getHeight();
}
// 建立對應大小的bitmap(重點)
bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
scrollView.draw(canvas);
return bitmap;
}
總結:
1. 佈局為ScrollView,ListView,RecyclerView等能滑動的,用for迴圈遍歷子元素求實際高度。
ps:ScrollView由於只能有一個直接子元素,那麼我們可以直接用他的子元素來求高度。
2. 佈局為LinearLayout等ViewGroup,直接.getHeight()獲取
注意:
1. getHeight(),getWidth()不能直接在avtivity生命週期中呼叫,因為activity尚未生成完畢之前,控制元件的長寬尚未測量,故所得皆為0
2. 用該方式實現長截圖需要注意背景色的問題,如果你的截圖背景色出了問題,仔細檢查XML檔案,看看該背景色是否設定在你截圖的控制元件中
補充:
對於混合佈局比如說:根RelativeLayout佈局中有ViewGroup+RelativeLayout等子佈局,可以分別測量他們的高度並生成bitmap物件,然後拼接在一起即可。
/**
* 上下拼接兩個Bitmap,
* drawBitmap的引數:1.需要畫的bitmap
* 2.裁剪矩形,bitmap會被該矩形裁剪
* 3.放置在canvas的位置矩形,bitmap會被放置在該矩形的位置上
* 4.畫筆
*/
public static Bitmap mergeBitmap_TB_My(Bitmap topBitmap, Bitmap bottomBitmap) {
int width = topBitmap.getWidth();
int height = topBitmap.getHeight() + bottomBitmap.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Rect rectTop = new Rect(0, 0, width, topBitmap.getHeight());
Rect rectBottomRes = new Rect(0, 0, width, bottomBitmap.getHeight());
RectF rectBottomDes = new RectF(0, topBitmap.getHeight(), width, height);
canvas.drawBitmap(topBitmap, rectTop, rectTop, null);
canvas.drawBitmap(bottomBitmap, rectBottomRes, rectBottomDes, null);
return bitmap;
}