Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a regular polygon so that one edge is parallel to the X axis?

I know that to draw a regular polygon from a center point, you use something along the lines of:

for (int i = 0; i < n; i++) {  
    p.addPoint((int) (100 + 50 * Math.cos(i * 2 * Math.PI / n)),
               (int) (100 + 50 * Math.sin(i * 2 * Math.PI / n))
              );
}

However, is there anyway to change this code (without adding rotations ) to make sure that the polygon is always drawn so that the topmost or bottommost edge is parallel to a 180 degree line? For example, normally, the code above for a pentagon or a square (where n = 5 and 4 respectively) would produce something like:

http://i.stack.imgur.com/Nv6Xf.gifhttp://i.stack.imgur.com/or967.gif

When what I'm looking for is:

http://i.stack.imgur.com/Tfxs1.gifhttp://i.stack.imgur.com/BIORA.gif

Is there any mathematical way to make this happen?

like image 659
Daniel Kang Avatar asked Mar 29 '11 00:03

Daniel Kang


1 Answers

You have to add Pi/2-Pi/n

k[n_] := Pi/2 - Pi/n;
f[n_] := Line[
   Table[50 {Cos[(2 i ) Pi/n + k[n]] ,Sin[(2 i) Pi/n + k[n]]}, {i,0,n}]];

GraphicsGrid@Partition[Graphics /@ Table[f[i], {i, 3, 8}], 3]  

enter image description here

Edit

Answering your comment, I'll explain how I arrived at the formula. Look at the following image:

enter image description here

As you may see, we want the middle point of a side aligned with Pi/2. So ... what is α? It's obvious

2 α = 2 Pi/n (one side) -> α = Pi/n

Edit 2

If you want the bottom side aligned with the x axis, add 3 Pi/2- Pi/n instead ...

enter image description here

like image 93
Dr. belisarius Avatar answered Jan 01 '23 14:01

Dr. belisarius