https://kotlinlang.org logo
#korge
Title
# korge
m

Michael Sigl

02/11/2021, 4:50 PM
How to draw a convex polygon in korge by just passing an array of vertices(Vec2 or Point)?
d

Deactivated User

02/12/2021, 6:37 AM
I believe you can use moveTo and lineTo and closePath commands in a graphics view. Don't remember if there is a function to do that directly already, but if not, you can create it as an extension method to VectorPath and would be super nice if you can make a PR to add it to the core
m

Michael Sigl

02/12/2021, 2:47 PM
Ok it works, but when I work with lineTo and moveTo, the polygon is just not filled, it has just a strokecolor along its path. How to fill this shape?
d

Deactivated User

02/12/2021, 2:54 PM
You have to wrap your code along fill(color) {...}
m

Michael Sigl

02/12/2021, 3:21 PM
Following code doesn't work: suspend fun main() = Korge { val data = arrayOf<Vec2>(Vec2(40f, 50f), Vec2(70f, 30f), Vec2(0f, 10f), Vec2(20f, 40f)) addChild(drawPolygon(this, data)) } fun drawPolygon(to: Container, path: Array<Vec2>): Graphics { return to.sgraphics { if (path.isNotEmpty()) { fill(Colors.YELLOW) { moveTo(path[0].x, path[0] .y) for (i in 1 until path.size) { line(path[i - 1].x, path[i - 1].y, path[i].x, path[i].y) } line(path[path.size - 1].x, path[path.size - 1].y, path[0].x, path[0].y) } } }
When I use fillStroke(), it works but just the lines without filled area
d

Deactivated User

02/12/2021, 8:06 PM
Okay, let me check
Copy code
fun drawPolygon(to: Container, path: Array<Vec2>): Graphics {
	return to.sgraphics {
		if (path.isNotEmpty()) {
			fill(Colors.YELLOW) {
				moveTo(path[0])
				for (i in 1 until path.size) {
					lineTo(path[i])
				}
				close()
			}
		}
	}
}
Once this PR is merged and KorGE version bumped: https://github.com/korlibs/korge-next/pull/168/files You could do something like:
Copy code
fun drawPolygon(to: Container, path: Array<Vec2>): Graphics {
	return to.sgraphics {
		if (path.isNotEmpty()) {
			fill(Colors.YELLOW) {
				polygon(path)
			}
		}
	}
}
m

Michael Sigl

02/12/2021, 9:18 PM
Thank you very much!
👍 1
30 Views