问题描述
如何使用画布在 Kotlin 中创建一个正方形的两个矩形和四个圆并调整其大小,直到它得到一个球或一个完美的正方形?
我们已经有了这个代码:
import pt.isel.canvas.*
private fun Canvas.drawSquare(r: RoundSquare) {
erase()
val f = (r.side/2 * r.round/100f).toInt()
val pos = Position(r.center.x,r.center.y)
val square =
drawRect(pos.x-150,pos.y-100,r.side+100,r.side,r.color)
drawRect(pos.x-100,pos.y-150,r.color)
drawCircle(pos.x-100,f,r.color)
drawCircle(pos.x+100,pos.y+100,r.color)
return square
}
fun main () {
onStart {
val cv = Canvas(600,400,WHITE)
var roundSquare = RoundSquare(Position(300,200),200,50,GREEN)
cv.drawSquare(roundSquare)
cv.drawText(10,"center=(${roundSquare.center.x},${roundSquare.center.y}) side=${roundSquare.side} round=${roundSquare.round}% color=0x${roundSquare.color.toString(16).padStart(6,'0').toupperCase()}",BLACK,15)
cv.onMouseDown {
roundSquare = roundSquare.copy(center = Position(it.x,it.y))
cv.drawSquare(roundSquare)
return@onMouseDown cv.drawText(10,390,15)
}
cv.onKeypressed {
roundSquare = roundSquare.processKey(it.char)
cv.drawSquare(roundSquare)
return@onKeypressed cv.drawText(10,15)
}
onFinish { println("Bye") }
}
}
import pt.isel.canvas.BLACK
import pt.isel.canvas.WHITE
data class Position (val x:Int,val y:Int)
data class RoundSquare (val center:Position,val side:Int,val round:Int,val color:Int)
val RANGE_SIZE = 10..400
val ROUND = 0..100
val RANDOM_COLOR = BLACK..WHITE
fun RoundSquare.processKey(key: Char) = when {
key=='r' && round > ROUND.first -> copy(round = round - 1,side = side -1)
key=='R' && round < ROUND.last -> copy(round = round + 1,side = side + 1)
key=='s' && side > RANGE_SIZE.first -> copy(side = side - 1,round = round - 1)
key=='S' && side < RANGE_SIZE.last -> copy(side = side + 1,round = round + 1)
key == 'c' -> copy(color = RANDOM_COLOR.random())
else -> this
}
可以通过调整边的大小和圆角来调整大小,直到它显示一个完美的球或完美的正方形。
如果有人能帮助我,我将不胜感激。
提前致谢,