BLOG.CSHARPHELPER.COM: Draw a chrysanthemum curve in C#
Draw a chrysanthemum curve in C#
This program uses the following equations to draw the chrysanthemum curve:
r = 5 * (1 + Sin(11 * t / 5)) - 4 * Sin(17 * t / 3)4 * Sin(2 * Cos(3 * t) - 28 * t)8 x = r * Cos(t) y = r * Sin(t)
The form's Paint event handler loops variable t through the values 0 to 21 * Pi to generate the curve's points and connects them. (Don't worry too much about how the equation works. Focus on how the program draws it.)
// Generate the points. double t = 0; double r = 5 * (1 + Math.Sin(11 * t / 5)) - 4 * Math.Pow(Math.Sin(17 * t / 3), 4) * Math.Pow(Math.Sin(2 * Math.Cos(3 * t) - 28 * t), 8); PointF pt1 = new PointF((float)(r * Math.Sin(t)), (float)(-r * Math.Cos(t)));
using (Pen the_pen = new Pen(Color.Blue, 0)) { for (int i = 0; i <= num_lines; i++) { t = i * Period * Math.PI / num_lines; r = 5 * (1 + Math.Sin(11 * t / 5)) - 4 * Math.Pow(Math.Sin(17 * t / 3), 4) * Math.Pow(Math.Sin(2 * Math.Cos(3 * t) - 28 * t), 8); PointF pt0 = pt1; pt1 = new PointF((float)(r * Math.Sin(t)), (float)(-r * Math.Cos(t))); the_pen.Color = GetColor(t); e.Graphics.DrawLine(the_pen, pt0, pt1); } } }
The code is reasonably straightforward (assuming you don't try to figure out the equation itself). It first scales and translates to make the curve fill the form. Then for each value of t, the code calculates the next point's X and Y coordinates and draws a segment connecting the point to the previous point. It calls the GetColor method to pick a color for the line.
The GetColor method returns a color selected from a pre-initialized array of colors.
// Return a color from the Colors array. private Color GetColor(double t) { return Colors[(int)(t / Math.PI)]; }
Comments