Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

language agnostic - How to draw a n sided regular polygon in cartesian coordinates?

I have been trying to figure out how to write a simple program to compute the x,y points for creating a regular polygon of n sides. Can someone give me some code examples that don't use preexisting functions that draw polygons? I want to understand the process, which I assume is something like this:

  1. pick an angle to start from a radius and a center point
  2. somehow calculate the x,y position at that distance from the center(how?)
  3. divide 360 by the number of sides, move that distance and draw the next line from the first x,y point
  4. continue until the angle=360 divided by that number.

Assuming that my assumptions are correct, the main thing is to understand how to compute the x,y points.

Prefer answers in a visual basic (or even old style Microsoft/Atari/Commodore BASIC) or a human readable set of steps in English. If you have to answer with a math formula, do it in a computer language so I can read it, even in C or C++ I can figure it out, but I don't know how to read mathematical notation. The language I'm using is a Visual Basic-like language that has almost no graphics primitives other than line drawing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's assume you want to draw an N-sided polygon of radius r, centred at (0,0). Then the n vertices are given by:

x[n] = r * cos(2*pi*n/N)
y[n] = r * sin(2*pi*n/N)

where 0 <= n < N. Note that cos and sin here are working in radians, not degrees (this is pretty common in most programming languages).

If you want a different centre, then just add the coordinates of the centre point to each (x[n], y[n]). If you want a different orientation, you just need to add a constant angle. So the general form is:

x[n] = r * cos(2*pi*n/N + theta) + x_centre
y[n] = r * sin(2*pi*n/N + theta) + y_centre

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...