从视图创建位图会使视图消失,如何获取视图画布?

cai*_*ci2 5 android canvas view bitmap

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

第一:

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;
}
Run Code Online (Sandbox Code Playgroud)

第二名:

Bitmap viewCapture = null;

theViewYouWantToCapture.setDrawingCacheEnabled(true);

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

theViewYouWantToCapture.setDrawingCacheEnabled(false);
Run Code Online (Sandbox Code Playgroud)

编辑

因此,我想我了解第一个情况,基本上是从原始画布中删除视图,并将其绘制到与该位图相关的其他位置。我们可以以某种方式存储原始画布,然后将视图设置为在此处重绘吗?

Guy*_*ith 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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