android 自定义视图覆盖 onDraw():canvas 将所有矩形绘制为黑色

android customview overriden onDraw(): canvas draws all rectangles black

我使用的自定义视图有问题。它绘制了一个网格,我用它来表示平面图,上面有一个开始位置和当前位置(彩色矩形)。 (此处代码: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(...) 方法的文档仅说明如下:

Draw the specified Rect using the specified paint. The rectangle will be filled or framed based on the Style in the paint.

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

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

尝试:

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

就像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);
    }

成功了。