我只是一个新手,正在尝试在Kotlin中使用 Canvas 。我试图根据将从其他 Activity 中获得的用户输入来绘制矩形。我不能做的就是将数组传递给重写类。这是我的代码。
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)
}
}
}
找到了,但是如果有更好的解决方案,我希望对其进行检查。