为什么我的绘图从 canvas 中消失了?

Why does my drawing disappear from a canvas?

我每 10 秒在 canvas 上画一些东西。不幸的是,它在重新绘制之前就消失了,所以我们有 10 秒的空白屏幕。我厌倦了在绘图和恢复之前保存 canvas,但没有帮助。 在我将一行 canvas.drawPath(linePath, linePaint); 从循环外部移入循环后出现此错误。

代码:

private void drawLine(Canvas canvas) {
        yStep = (yHeight) / fullChargeLevel;
        xStep = (xWidth) / timeStampBarsQuantity;

        boolean check = false;
        float time;
        float chrg;

        while (batteryUsageHistory != null && batteryUsageHistory.moveToNext()) {
            int charge = batteryUsageHistory.getInt(1);
            int time_stamp = batteryUsageHistory.getInt(2);

            if (charge < 1) {

                if(check){
                    canvas.drawPath(linePath, linePaint); //This line I shifted into here
                    linePath.reset();
                }

                check = false;

                continue;
            }

            time = xPos + time_stamp * xStep;
            chrg = yPos - (charge * yStep);

            if (!check) {
                linePath.moveTo(time, chrg);
                check = true;

                continue;
            }
            linePath.lineTo(time, chrg);
        }
        //canvas.drawPath(linePath, linePaint); //This line I shifted from here
    }

您应该通过扩展一些视图在 onDraw 中实现您的绘图逻辑 class:

protected void onDraw(Canvas canvas) {
   // here goes your custom drawing logic
}

如所述:https://developer.android.com/training/custom-views/custom-drawing.html

这是因为android在需要的时候重绘组件。总好比你要实现绘图方法,GUI框架会在需要的时候调用这个方法,不是相反,GUI框架显示你的画,它只是在需要的时候调用你的绘图方法。

我刚搬回那条线canvas.drawPath(linePath, linePaint);我以前搬过。并且有效!