5

我发现了两种从视图创建位图的方法。但是一旦我这样做,视图就会消失,我不能再使用它了。生成位图后如何重绘视图?

第一个:

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);

编辑

所以,我想我理解第一个会发生什么,我们基本上是从原始画布中删除视图并将其绘制到与该位图相关的其他位置。我们可以以某种方式存储原始画布,然后将视图设置为在那里重绘吗?

4

3 回答 3

3

抱歉,我对这方面不是很了解。但我使用以下代码:

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;
}

这与您的非常相似,我怀疑我们是从同一个地方复制和编辑的。

我对视图从原始绘图树中消失没有任何问题。我的被​​称为 ViewGroups 而不是普通的 Views。

于 2013-01-25T14:40:03.280 回答
1

尝试这个。

获取位图:

// 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; 
于 2013-01-25T16:45:27.990 回答
0

Guy's answer works when the View has not yet been laid out in a parent view. If the view already has been measured and laid out in a parent-view, Guy's answer may screw up your Activity's layout. If the view hasn't yet been measured and laid out, Guy's answer works fine.

My answer would work after the View has been laid out and it won't screw up the Activity's layout since it doesn't measure and layout the View again.

于 2013-01-28T15:24:35.323 回答