Reputation: 526
I'm writing a drawing program and one feature I would like to implement is arbitrarily sided shapes. I have most of the features worked out, but one thing I need is a function to generate a Polygon
object from an integer representing a number of sides. I don't remember much of trigonometry, although I'm sure that my problem involves some.
Upvotes: 1
Views: 588
Reputation: 57381
Hope this helps. It provides code for regular polygons. http://java-sl.com/shapes.html
Upvotes: 2
Reputation: 30828
There are two parts to your problem. First, you need an algorithm for generating points that comprise vertices of a polygon, which is a language-agnostic process. Based on the wording of your question, it seems like any polygon with the required number of sides works, so you could generate a regular polygon based on a circle of fixed radius.
For example, for the input 4
, your points might be (0, r)
, (r, 0)
, (0, -r)
and (-r, 0)
. You'd get those by drawing an imaginary/invisible circle of radius r
, then selecting points (sin(360/input)*r, cos(360/input)*r)
. (Keep in mind that Java's trig uses radians, not degrees, though.)
Once you have your points, you have to create the Polygon
object. There's a constructor that takes an array of x-coordinates and an array of y-coordinates, plus the total number of vertices, which is just your initial input. All you really have to do is pop the coordinates of your points into two arrays and you're all set.
Upvotes: 2