位图 onDraw() 不更新

bitmap onDraw() not updating

我试图在视图中显示一个蓝色方块,然后显示一个红色方块。

问题是当它应该画一个蓝色方块时没有画任何东西,但是当它应该画一个红色方块时,它没有画蓝色方块。

我在这里错过了什么?

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if(runCount == 1)
    {
        // Color blue and save bitmap
        blueCanvas = new Canvas();
        blueBitmap = Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(),Bitmap.Config.RGB_565);
        canvas.drawRect(0, 0 , 200, 300, bgPaintBlue);
    }
    if(runCount == 2){
        // Color red
        redCanvas = new Canvas();
        redBitmap = Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(),Bitmap.Config.RGB_565);
        canvas.drawRect(0, 0 , 200, 300, bgPaintRed);
    }
    runCount++;
    invalidate();
}

直接来自文档:

public void invalidate ()

Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future.

https://developer.android.com/reference/android/view/View.html#invalidate()

如前所述,您在 onDraw 方法本身内部调用 invalidate,因此它创建了一个无限循环。同时,您也在其中更新 runCount,因此它会不断增加该变量。

虽然我不确定你到底想做什么,但我建议至少删除声明

invalidate();

从 onDraw 方法内部重新考虑您的设计。只要您引用了此视图,就可以从程序的其他地方调用 invalidate,但请确保调用在 UI(主)线程上。

如果要在canvas上绘制位图,需要将位图附加到canvas,然后根据需要快速绘制。

    private Bitmap canvasBitMap = null;
    private Canvas bitmapCanvas = null;
      @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);


    int paddingLeft = getPaddingLeft();
    int paddingTop = getPaddingTop();
    int paddingRight = getPaddingRight();
    int paddingBottom = getPaddingBottom();

    int contentWidth = getWidth() - paddingLeft - paddingRight;
    int contentHeight = getHeight() - paddingTop - paddingBottom;

    mgraphWidth     = contentWidth;
    mgraphHeight    = contentHeight;

    if(canvasBitMap == null)
    canvasBitMap = Bitmap.createBitmap(mgraphWidth, mgraphHeight, Bitmap.Config.ARGB_8888);

    if(bitmapCanvas == null)
        bitmapCanvas = new Canvas(canvasBitMap);

    canvas.drawBitmap(canvasBitMap,0,0,mgraphcolor);

    drawGraph(bitmapCanvas);
}

您可以使用这个完整的 GitHub 代码来理解 graph/UI 使用 CustomView 的绘图。

分叉此存储库并将其用作样板文件。

https://github.com/Teju068/Android_Tutotrial