沿 canvas? 的整个高度绘制垂直线?

Draw vertical line along the entire height of the canvas?

我有以下代码:

class Canvass(context: Context) : View(context) {

    override fun onDraw(canvas: Canvas) {

        canvas.drawRGB(255, 255, 255)

        val width = width
        val height = height

        val paint = Paint()

        var offset = 50
        paint.setARGB(255, 0, 0, 0)

        paint.setStrokeWidth(2f)

        for (i in 0..100) {
            canvas.drawLine(0f, 30f + offset, width.toFloat(), 30f + offset, paint)
            offset += 40

        }

        canvas.drawLine(150f, 0f, width.toFloat(), height.toFloat() , paint)

    }
}

它产生以下内容:

但我希望结果中的 倾斜 行是垂直的。

当我改变时:

canvas.drawLine(150f, 0f, width.toFloat(), height.toFloat() , paint)

类似于:

canvas.drawLine(150f, 0f, width.toFloat(), 16000F, paint)

它更接近垂直但仍然倾斜:

canvas.drawLine(150f, //Start at x == 150
        0f, // And y = 0
        width.toFloat(),// Continue to x = width 
        height.toFloat(), //And y = height

        paint) // Not relevant to the position

您的 x 值必须匹配才能垂直。 X 是匹配宽度的值。当你的 x 值为 150,宽度为 1 时,它最终会变成这样。

直线始终具有匹配的 x y 坐标,具体取决于方向。因此,要使其正常工作,您需要将 width.toFloat() 更改为 150f 或其他值。


我还强烈建议您阅读坐标系。你可以看看this。虽然它涵盖了 Java 代码,但它仍然是 Android 上的同一个系统。