spring like drawing in c#

2019-08-02 19:36发布

问题:

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

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

回答1:

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


回答2:

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.