【问题标题】:bitmap onDraw() not updating位图 onDraw() 不更新
【发布时间】:2018-09-10 03:12:30
【问题描述】:

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

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

我在这里错过了什么?

@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();
}

【问题讨论】:

  • 您不需要从 onDraw 方法调用 invalidate();。也不明白你到底想做什么,请详细说明
  • 在阅读了一些关于画布、位图等的理论之后,我只是想研究一下这个机制是如何工作的。但我无法理解这个小例子

标签: android draw


【解决方案1】:

直接来自文档:

公共无效无效()

使整个视图无效。如果视图可见,onDraw(android.graphics.Canvas) 将在未来的某个时间点被调用。

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

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

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

invalidate();

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

【讨论】:

  • 最后,解决方案应该创建一条连续的线。我只是想了解它是如何更新位图的
【解决方案2】:

如果你想在画布上绘制位图,你需要将位图附加到画布上,然后尽可能快地绘制。

    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 代码来理解使用 CustomView 绘制的图形/UI。

fork 这个存储库并将其用作样板。

https://github.com/Teju068/Android_Tutotrial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多