【问题标题】:android customview overriden onDraw(): canvas draws all rectangles blackandroid自定义视图覆盖onDraw():画布将所有矩形绘制为黑色
【发布时间】:2017-06-21 17:27:59
【问题描述】:

我使用的自定义视图有问题。它绘制了一个网格,我用它来表示平面图,上面有一个开始和当前位置(彩色矩形)。 (此处代码:https://pastebin.com/8SExmtAp)。

简而言之,我像这样初始化不同的绘画:

 private void initPaints()
{
    waypointPaint = new Paint(Color.parseColor("#800080"));
    currentCoordinatePaint = new Paint(Color.RED);
    linePaint = new Paint(Color.BLACK);
    startCoordinatePaint = new Paint(Color.BLUE);
}

并像这样在 onDraw() 中使用它们:

    // color the current coordinates
    Coordinates currentCoords = Model.getCurrentCoordinates();
    if (currentCoords != null)
    {
                canvas.drawRect((float) currentCoords.getX() * cellWidth, (float) currentCoords.getY() * cellHeight,
                        (float) (currentCoords.getX() + 1) * cellWidth, (float) (currentCoords.getY() + 1) * cellHeight,
                        currentCoordinatePaint);

    }

    Coordinates startCoordinate = Model.startCoordinate;
    if (startCoordinate != null && startCoordinate != currentCoords)
    {
        canvas.drawRect((float) startCoordinate.getX() * cellWidth, (float) startCoordinate.getY() * cellHeight,
                (float) (startCoordinate.getX() + 1) * cellWidth, (float) (startCoordinate.getY() + 1) * cellHeight,
                startCoordinatePaint);
    }

但是,开始位置不是蓝色的,当前位置是红色的,它们都是黑色的,请参阅: Screenshot of app

关于我使用的 drawRect(...) 方法的文档只说明了以下内容:

使用指定的paint绘制指定的Rect。矩形将根据绘画中的样式进行填充或加框。

所以..我真的不知道代码哪里错了,为什么我会得到我得到的结果。也许你们当中有人知道为什么?

【问题讨论】:

    标签: android canvas paint ondraw


    【解决方案1】:

    Paint constructor you are using 需要 int 标志作为参数,而不是填充颜色。

    试试:

    currentCoordinatePaint = new Paint();
    currentCoordinatePaint.setStyle(Paint.Style.FILL);
    currentCoordinatePaint.setColor(Color.RED);
    

    【讨论】:

    • 哦……我明白了。我一回到家就试试。谢谢
    • 差点忘了报告。你是绝对正确的,改变绘画初始化做到了。
    • Paint.Style.FILL 现在似乎是默认设置,所以如果你想要的话,不需要使用setStyle。 ;)
    【解决方案2】:

    就像 josef.adamcik statet 一样,我对用于绘制对象的构造函数有误。将代码更改为

    private void initPaints()
        {
            waypointPaint = new Paint();
            waypointPaint.setColor(Color.GREEN);
            waypointPaint.setStyle(Paint.Style.FILL);
            currentCoordinatePaint = new Paint();
            currentCoordinatePaint.setColor(Color.RED);
            currentCoordinatePaint.setStyle(Paint.Style.FILL);
            linePaint = new Paint();
            linePaint.setColor(Color.BLACK);
            linePaint.setStyle(Paint.Style.STROKE);
            startCoordinatePaint = new Paint();
            startCoordinatePaint.setColor(Color.BLUE);
            startCoordinatePaint.setStyle(Paint.Style.FILL);
        }
    

    成功了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2014-05-06
      相关资源
      最近更新 更多