How to draw a convex polygon in korge by just pass...
# korge
m
How to draw a convex polygon in korge by just passing an array of vertices(Vec2 or Point)?
d
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
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
You have to wrap your code along fill(color) {...}
m
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
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
Thank you very much!
👍 1