Polygon View



  • In the case you want to generate symmetric polygons like pentagons, hexagons and so on:

    inline fun Container.polygon(
    		radius: Double = 16.0,
    		sides: Int = 5,
    		color: RGBA = Colors.WHITE,
    		autoScaling: Boolean = true,
    		callback: Polygon.() -> Unit = {}
    ): Polygon = Polygon(radius, sides, color, autoScaling).addTo(this).apply(callback)
    
    class Polygon(
    	radius: Double = 16.0,
    	sides: Int = 5,
    	color: RGBA = Colors.WHITE,
    	autoScaling: Boolean = true
    ) : Graphics(autoScaling = autoScaling) {
    	/** Radius of the circle */
    	var radius: Double by uiObservable(radius) { updateGraphics() }
    
    	/** Number of sides of the polygon */
    	var sides: Int by uiObservable(sides) { updateGraphics() }
    
    	/** Color of the circle. Internally it uses the [colorMul] property */
    	var color: RGBA
    		get() = colorMul
    		set(value) { colorMul = value }
    
    	override val bwidth get() = radius * 2
    	override val bheight get() = radius * 2
    
    	init {
    		this.color = color
    		updateGraphics()
    	}
    
    	private fun updateGraphics() {
    		clear()
    		fill(Colors.WHITE) {
    			for (n in 0 until sides) {
    				val angle = ((360.degrees * n) / sides) - 90.degrees
    				val x = radius * angle.cosine
    				val y = radius * angle.sine
    				//println("$x, $y")
    				if (n == 0) {
    					moveTo(x, y)
    				} else {
    					lineTo(x, y)
    				}
    			}
    			close()
    		}
    	}
    }
    

Log in to reply