2013-01-02 17 views
0

我知道你可以在運行時改變一個控件的x/y位置,我可以使用一個定時器來向上/向下/向左/向右/對角地移動它,但是你怎樣才能以編程方式將它移動一圈?在運行時將控件移動一圈?

例如,如果我在主窗體的12點鐘位置有一個PictureBox控件,我可以將該圖片框移動一個圓圈,在其開始位置完成,點擊一個按鈕?

+0

答:是的,可以。 –

+0

你想詳細說明我該怎麼做? – iajs

+0

如果你可以垂直和水平移動一個控件,你也可以將它移動一圈:) – dasblinkenlight

回答

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

非常感謝你! – iajs

+0

你知道我應該朝哪個方向讓一組控件沿着相同的路徑移動嗎? – iajs

+0

@ user1679851從'UserControl'派生而不是'PictureBox'。從技術上講,你也可以從'Panel'或其他容器派生。 – Mir

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