views:

79

answers:

2

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

alt text

+2  A: 

First of all you'd need to think of a formula that would represent the spring. You could draw a circle and as you're going around it, let the X increase a bit. For instance:

        for (double i = 0; i < 50; i += 0.01)
        {
            int x = (int)(Math.Sin(i) * 10 + i * 3);
            int y =(int)(Math.Cos(i) * 10 + 50);
        }

See the i variable there as time, and the result x and y the coordinates to draw; you'd traverse the path of the spring in small steps.

You could then create a new Bitmap and use the SetPixel method on those coordinates, and in the OnPaint method of your form, draw the bitmap on it.

If you're any good with math (I'm not :P) you might be able to only plot pixels inside the bitmap - the above example doesn't solve the problem of the minimum and maximum values for i.

deltreme
With setPixel approach the step will have to be very small in order to create a continuous drawing (spring), and some tweaking will be required in order to avoid pixel art :) With the drawlines approach (see my answer) a larger step will be sufficient for producing a convincing shape.
Rekreativc
Agreed :] There's lots of things to play around with, I could imagine calculating only one "circle" and copying it to speed things up.
deltreme
A: 

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());
}
Rekreativc