canvas.drawRect如何绘制矩形

How canvas.drawRect draws a rectangle

我必须创建一个自定义视图,我必须在其中绘制一个矩形。我正在尝试使用 canvas.drawRect 方法。我想创建这样的矩形

灰色的是我的自定义视图,它扩展了 View class。 在 onDraw 方法中,我正在尝试绘制矩形。

但实际上我对drawRect方法的参数感到困惑。

根据文档

/**
 * Draw the specified Rect using the specified paint. The rectangle will
 * be filled or framed based on the Style in the paint.
 *
 * @param left   The left side of the rectangle to be drawn
 * @param top    The top side of the rectangle to be drawn
 * @param right  The right side of the rectangle to be drawn
 * @param bottom The bottom side of the rectangle to be drawn
 * @param paint  The paint used to draw the rect
 */

我假设left和top构成起点的x,y坐标,right是宽度,bottom是高度。但它似乎不是那样工作的。

我试过类似的方法来绘制一个矩形,但它没有绘制任何东西

       paint.setColor(Color.BLUE);
       canvas.drawRect(5, canvas.getHeight()/2, 30, 30, paint );

谁能告诉我如何使用这些值绘制矩形?

如果有人能展示至少绘制第一个矩形的代码,那将非常有帮助。

我的要求是,内部矩形的数量是动态的,所以如果我将一些 4 传递给这个视图,它应该水平创建 4 个等宽的矩形。像

提前致谢!!

drawRect(float left, float top, float right, float bottom, Paint paint)

在你的情况下,问题似乎是如果 right 小于 leftbottom 小于 top 则不绘制矩形。但它似乎只发生在某些设备上,正如@David Medenjak 评论的那样

我还建议您使用视图尺寸而不是 Canvas 尺寸,最好使用 getWidth() 和 getHeight() 而不是 Canvas.getWidth() 和 Canvas.getHeight()

But actually I'm confused with the parameters of the drawRect method.

drawRect方法只需要两个坐标就可以画出一个矩形。 左上角和右下角。所以这4个点形成了这2个坐标 在你的 canvas 中。希望从下面的图片中看得清楚

P1和P2是由(left,top)和(right,bottom)组成的点,所以画出来的矩形是这样的

要像图片中显示的那样动态绘制矩形,请尝试这样的操作

int[] colors = new int[]{Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW}; // given some fixed colors

在你onDraw方法

@Override
protected void onDraw(Canvas canvas) {
int padding = 5;
float rectangleWidth = (getMeasuredWidth() - padding * 2) / colors.length;
for (int i = 0; i < colors.length; i++) {
    paint.setColor(colors[i]);
    canvas.drawRect(padding + (rectangleWidth * i),
                    getMeasuredHeight() / 2,
                    padding + rectangleWidth * (i + 1),
                    getMeasuredHeight() - padding, paint
    ); // 5 px is the padding given to the canvas
}

}

使用此方法在具有宽度和高度参数的 X 和 Y 坐标处绘制矩形

fun drawRectangle(left: Int, top: Int, right: Int, bottom: Int, canvas: Canvas, paint: Paint?) {
        var right = right
        var bottom = bottom
        right = left + right // width is the distance from left to right
        bottom = top + bottom // height is the distance from top to bottom
        canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint!!)
    }

用法

//绘制矩形

        drawRectangle(posX, posY, 60, 40, canvas, paint)