如何在 Kotlin 中绘制矩形?

How to draw rectangles in Kotlin?

我只是一个新手,正在尝试在 Kotlin 中使用 canvas。我正在尝试根据我将从另一个 activity 获得的用户输入绘制矩形。我不能做的是将数组传递给覆盖 class。这是我的代码。

fun drawrect(view: View){
    val layout1 = findViewById<ConstraintLayout>(R.id.layout1)
    val background = Canvass (this)
    layerheight = getIntent().getSerializableExtra("layerheight") as ArrayList<Double>;
    soilspecificweight = getIntent().getSerializableExtra("soilspecificweight") as ArrayList<Double>;
    cohesion= getIntent().getSerializableExtra("cohesion") as ArrayList<Double>;
    frictionangle = getIntent().getSerializableExtra("frictionangle") as ArrayList<Double>;
    mpeffectivestress = getIntent().getSerializableExtra("mpeffectivestress") as ArrayList<Double>;
    voidratio = getIntent().getSerializableExtra("voidratio") as ArrayList<Double>;
    compressionindex = getIntent().getSerializableExtra("compressionindex") as ArrayList<Double>;
    recompressionindex = getIntent().getSerializableExtra("recompressionindex") as ArrayList<Double>;
    bearingcapacityindex = getIntent().getSerializableExtra("bearingcapacityindex") as ArrayList<Double>;
    layout1.addView (background)

}
class Canvass (context: Context): View(context) {
    override fun onDraw (canvas: Canvas) {
        canvas.drawRGB (255, 255, 255)
        val width = width
        val footingpaint = Paint ()
        val textpaint = Paint ()
        val brush3 = Paint ()
        val brush4 = Paint ()

        footingpaint.setARGB (255, 128, 128, 128)
        textpaint.setARGB (255, 255, 255, 255)
        brush3.setARGB (255, 138, 36, 36)
        brush4.setARGB (255, 138, 36, 36)

        canvas.drawRect (((width/2)-10).toFloat(), 0f, ((width/2)+ 10) .toFloat (), 40f, footingpaint)
        canvas.drawRect (70f, 40f, (width - 70) .toFloat (), 80f, footingpaint)
        for(i in (0..layerheight.size)){

        }



    }
}
class Canvass (context: Context, layerheight: ArrayList<Double>): View(context) {

    private var layerheight: ArrayList<Double> = layerheight
    override fun onDraw (canvas: Canvas) {

        canvas.drawRGB (255, 255, 255)
        val width = width
        val footingpaint = Paint ()
        val textpaint = Paint ()
        val brush3 = Paint ()
        val brush4 = Paint ()

        footingpaint.setARGB (255, 128, 128, 128)
        textpaint.setARGB (255, 255, 255, 255)
        brush3.setARGB (255, 138, 36, 36)
        brush4.setARGB (255, 138, 36, 36)

        canvas.drawRect (((width/2)-10).toFloat(), 0f, ((width/2)+ 10) .toFloat (), 40f, footingpaint)
        canvas.drawRect (70f, 40f, (width - 70) .toFloat (), 80f, footingpaint)
        for(i in (0..layerheight.size)){
            println(layerheight)
        }

    }
}

找到了,但如果有更好的解决方案,我很乐意查看。