Search code examples
c#mathdrawingsystem.drawingshapes

spring like drawing in c#


How to draw the spring like shape using c# drawing class

alt text http://img812.imageshack.us/img812/373/spring.jpg


Solution

  • This is more of a math problem than a C# one. What you want is to derive a Parametric equation for the curve you wish to draw.

    With that go and fill an array of Point objects with values for the parametric equation on a certain interval with a certain step (the smaller the step the more the final drawing will look like the actual shape). Then you can use g.DrawLines (MSDN: DrawLines) to draw the actual curve on a surface.

    You can edit the width, color and other properties of the line by modifying parameters of the Pen object.

    Your actual code would look like this:

    void DrawSpring (Graphics g)
    {
        List<Point> points = new List<Point>();
    
        double step = 0.01;
        for(double t = -2; t < 2; t += step)
        {
            Point p = new Point();
            p.X = XPartOfTheEquation(t);
            p.Y = YPartOfTheEquation(t);
    
            points.Add(p);
         }
    
        g.DrawLines(new Pen(new SolidBrush(Color.Black), 2f), points.ToArray());
    }