如何在 Kotlin 中对两个矩形和四个圆进行圆角和调整大小以创建一个正方形?

问题描述

我正在学习 Kotlin,我在这里面临一个挑战:

如何使用画布在 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
}

但它没有给我我需要的输出。这是输出

enter image description here

可以通过调整边的大小和圆角来调整大小,直到它显示一个完美的球或完美的正方形。

如果有人能帮助我,我将不胜感激。

提前致谢,

解决方法

设圆形中心为(cx,cy),半尺寸为hs

enter image description here

左 x 坐标为 lx = cx - hs
顶部 y 坐标为 ty = cy - hs
右 x 坐标为 rx = cx + hs
底部 y 坐标为 by = cy + hs

我们希望将参数 t 从 0 更改为 1(或从 0 更改为 100%)以获得所需的圆度。

圆的半径是(如果需要,可以舍入到整数)

R = hs * t

圆心坐标:

lx + R,ty + R
rx - R,by - R
lx + R,by - R

矩形的两个角:

(lx + R,ty) - (rx - R,by) 
(lx,ty + R) - (rx,by - R)