【问题标题】:Move a control in a circle at runtime?在运行时将控件移动一圈?
【发布时间】:2013-01-02 22:17:06
【问题描述】:

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

例如,如果我在主窗体的 12 点钟位置有一个 PictureBox 控件,我可以在单击按钮时将那个图片框移动成一个圆圈,在其起始位置完成吗?

【问题讨论】:

  • 您想详细说明我会怎么做吗?
  • 如果你可以垂直和水平移动一个控件,你也可以在一个圆圈中移动它:)
  • 是的,我知道,难点在于它的逻辑。这就是我寻求帮助的原因。

标签: c# winforms animation picturebox


【解决方案1】:

使用正弦和余弦函数。

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

结果:

【讨论】:

    【解决方案2】:

    我已经编写了一个源自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();
    }
    

    【讨论】:

    • 你知道我应该朝哪个方向让一组控件沿着同一路径移动吗?
    • @user1679851 派生自 UserControl 而不是 PictureBox。从技术上讲,您还可以从 Panel 或其他容器派生。
    • 那么对容器中的每个控件应用相同的RotateStep函数?感谢您的所有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2013-07-30
    相关资源
    最近更新 更多