1. 程式人生 > >Android獲取View的內容圖片

Android獲取View的內容圖片

1 獲取當前可見的View的圖片,類似於手機截圖

View dView = getWindow().getDecorView();//獲取DecorView
dView.setDrawingCacheEnabled(true);//生成View的副本,是一個BitmapBitmap bmp = dView.getDrawingCache();//獲取View的副本,就是這個View上面所顯示的任何內容


2 獲取任意View的內容圖片

Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888
); Canvas c = new Canvas(b);//使用bitmap構建一個Canvas,繪製的所有內容都是繪製在此Bitmap上的 Drawable bgDrawable = v.getBackground(); bgDrawable.draw(c);//繪製背景view.draw(c);//繪製前景 return bitmap; 如果是ListView,ScrollView,Webview等高度不固定的View,還需要手動計算出來高度來建立Bitmap,其他步驟相同
for (int i = 0; i < listView.getChildCount(); i++) {
    h += listView.getChildAt(i).getHeight();
}
// 建立對應大小的bitmap
bitmap = Bitmap.createBitmap(listView.getWidth(), h, Bitmap.Config.ARGB_8888);

示例程式碼
//組合view
private Bitmap combineView(View topView, WebView centerView, View bottomView) {

    float topWidth = topView.getWidth();
    float topHeight = topView.getHeight();

    float centerWidth = centerView.getWidth();
    float 
centerHeight = centerView.getContentHeight() * centerView.getScale(); float bottomWidth = bottomView.getWidth(); float bottomHeight = bottomView.getHeight(); float width = Math.max(topWidth, Math.max(centerWidth, bottomWidth));//取最大的寬度作為最終寬度 float height = topHeight + centerHeight + bottomHeight;//計算總高度 Bitmap topBitmap = Bitmap.createBitmap((int) width, (int) topHeight, Bitmap.Config .ARGB_8888);//頂部圖片 topView.draw(new Canvas(topBitmap)); Bitmap centerBitmap = Bitmap.createBitmap((int) width, (int) centerHeight, Bitmap.Config .ARGB_8888);//中部圖片 centerView.draw(new Canvas(centerBitmap)); Bitmap bottomBitmap = Bitmap.createBitmap((int) width, (int) bottomHeight, Bitmap.Config .ARGB_8888);//底部圖片 bottomView.draw(new Canvas(bottomBitmap)); Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);//底圖 Canvas canvas = new Canvas(bitmap);//畫布 Paint paint = new Paint(); canvas.drawBitmap(topBitmap, 0, 0, paint);//畫頂部 canvas.drawBitmap(centerBitmap, 0, topHeight, paint);//畫中間 canvas.drawBitmap(bottomBitmap, 0, topHeight + centerHeight, paint);//畫底部 return bitmap; }