在运行时将控件移动到圆圈中?

时间:2013-01-02 13:47:21

标签: c# winforms animation picturebox

我知道您可以在运行时更改控件的x / y位置,我可以使用计时器上/下/左/右/对角移动它但是如何以编程方式将其移动到圆圈中?

例如,如果我在主表单上的12点钟位置有一个PictureBox控件,我可以将该图片框移动一个圆圈,在其开始位置结束,点击一下按钮吗?

2 个答案:

答案 0 :(得分:4)

使用鼻窦和余弦函数。

例如,请查看that

具体的C#示例存在here。 如果某天链接不存在,这里是在表单上绘制25个增加半径圆的源代码:

void PutPixel(Graphics g, int x, int y, Color c)
{
      Bitmap bm = new Bitmap(1, 1);
      bm.SetPixel(0, 0, Color.Red);
      g.DrawImageUnscaled(bm, x, y);
}

private void Form1_Paint(object sender, PaintEventArgs e)
{  
      Graphics myGraphics = e.Graphics;

      myGraphics.Clear(Color.White);
      double radius = 5;
      for (int j = 1; j <= 25; j++)
      {
            radius = (j + 1) * 5;
            for (double i = 0.0; i < 360.0; i += 0.1)
            {
                double angle = i * System.Math.PI / 180;
                int x = (int)(150 + radius * System.Math.Cos(angle));
                int y = (int)(150 + radius * System.Math.Sin(angle));

                PutPixel(myGraphics, x, y, Color.Red);
            }
      }
      myGraphics.Dispose();
}

<强>结果:

enter image description here

答案 1 :(得分:1)

我写了一个源自PictureBox的小班,可以让你轻松地达到你的成绩。每次拨打RotateStep时,其位置都会相应更改。角度和速度以弧度表示,距离以像素为单位。

class RotatingPictureBox : PictureBox
{
    public double Angle { get; set; }
    public double Speed { get; set; }
    public double Distance { get; set; }

    public void RotateStep()
    {
        var oldX = Math.Cos(Angle)*Distance;
        var oldY = Math.Sin(Angle)*Distance;
        Angle += Speed;
        var x = Math.Cos(Angle)*Distance - oldX;
        var y = Math.Sin(Angle)*Distance - oldY;
        Location += new Size((int) x, (int) y);
    }
}

样本用法:

public Form1()
{
    InitializeComponent();
    var pictureBox = new RotatingPictureBox
    {
        Angle = Math.PI,
        Speed = Math.PI/20,
        Distance = 50,
        BackColor = Color.Black,
        Width = 10,
        Height = 10,
        Location = new Point(100, 50)
    };
    Controls.Add(pictureBox);
    var timer = new Timer {Interval = 10};
    timer.Tick += (sender, args) => pictureBox.RotateStep();
    timer.Start();
}