2013-01-24 71 views
2

我發現了兩種從視圖創建位圖的方法。但一旦我這樣做,視圖就消失了,我不能再使用它了。如何在生成位圖後重新繪製視圖?從視圖創建位圖使視圖消失,如何獲取視圖畫布?

1:

public static Bitmap getBitmapFromView(View view) { 
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888); 
Canvas canvas = new Canvas(returnedBitmap); 
Drawable bgDrawable =view.getBackground(); 
if (bgDrawable!=null) 
    bgDrawable.draw(canvas); 
else 
    canvas.drawColor(Color.WHITE); 
view.draw(canvas); 
return returnedBitmap; 
} 

第二:

Bitmap viewCapture = null; 

theViewYouWantToCapture.setDrawingCacheEnabled(true); 

viewCapture = Bitmap.createBitmap(theViewYouWantToCapture.getDrawingCache()); 

theViewYouWantToCapture.setDrawingCacheEnabled(false); 

編輯

所以,我想我明白在第一個會發生什麼,我們基本上消除了認爲從它的原始畫布並將其繪製在與該位圖相關的其他位置。可以以某種方式存儲原始畫布,然後將視圖設置爲在那裏重繪?

回答

2

對不起,我對此不是非常瞭解。但是我用下面的代碼:

public Bitmap getBitmapFromView(View view, int width, int height) { 
    Bitmap returnedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(returnedBitmap); 
    Drawable bgDrawable = view.getBackground(); 
    if (view==mainPage.boardView) { 
     canvas.drawColor(BoardView.BOARD_BG_COLOR); 
    } else if (bgDrawable!=null) { 
     bgDrawable.draw(canvas); 
    } else { 
     canvas.drawColor(Color.WHITE); 
    } 
    view.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); 
    view.layout(0, 0, width, height); 
    view.draw(canvas); 
    return returnedBitmap; 
} 

是如此的相似,你我懷疑我們複製&來自同一個地方進行編輯。

我沒有麻煩,視圖從原始繪圖樹中消失。 Mine被稱爲ViewGroups而不是普通的Views。

+0

Thanks @Guy Smith,工作正常,我缺少的是在提取位圖後重新佈局視圖! view.layout(0,0,width,height);! – caiocpricci2

0

試試這個。

獲取位圖:

// Prepping. 
boolean oldWillNotCacheDrawing = view.willNotCacheDrawing(); 
view.setWillNotCacheDrawing(false); 
view.setDrawingCacheEnabled(true); 
// Getting the bitmap 
Bitmap bmp = view.getDrawingCache(); 

,並確保視圖重置回其原來的自我。

view.destroyDrawingCache(); 
view.setDrawingCacheEnabled(false); 
view.setWillNotCacheDrawing(oldWillNotCacheDrawing);  

return bmp; 
+0

上面代碼片段中的主要內容是調用'view.setWillNotCacheDrawing(false)'。例如。如果'view'是一個ImageView,只調用'view.setDrawingCacheEnabled(true)'調用是不夠的。在這種情況下,需要調用setWillNotCacheDrawing。 –

0

Guy的答案適用於視圖尚未放在父視圖中時。 如果視圖已經被測量並且以父視圖的形式進行了佈置,那麼Guy的答案可能會搞砸你的Activity的佈局。 如果該視圖尚未測量和佈局,Guy的答案正常。

我的答案將工作之後視圖已經佈局,它不會搞砸活動的佈局,因爲它不會再次測量和佈局視圖。