简体   繁体   中英

Drawing Arbitrarily Sided Shape

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.

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.

Hope this helps. It provides code for regular polygons. http://java-sl.com/shapes.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM