本文實例為大家分享了Android實現全屏截圖或長截屏功能的具體代碼,供大家參考,具體內容如下
全屏截圖:
/*** 傳入的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; }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答