C#GDI旋转弹丸

时间:2015-06-27 19:31:08

标签: c# user-interface gdi+ gdi

我有这段代码

Graphics g;
g.FillRectangle(new SolidBrush(Color.Red), _Location.X - 2, _Location.Y - 2, 10, 10);

并且矩形以某个角度向某个方向拍摄,如何在移动或旋转时让矩形旋转。

2 个答案:

答案 0 :(得分:1)

这应该旋转一个在屏幕上移动的矩形。

private int _angle = 0;
private Point _location = new Point(0, 0);

private void _timer_Tick(object sender, System.EventArgs e)
{
    // nothing interesting here, moving the top left co-ordinate of the         
    // rectangle at constant rate
    _location = new System.Drawing.Point(_location.X + 2, _location.Y + 2);
    _angle += 5; // our current rotation angle
    this.Invalidate();
}

void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;            
    // rebase the co-ordinate system so our current x,y is 0, 0 and that is   
    // the center of the rotation
    g.TranslateTransform(_location.X, _location.Y, MatrixOrder.Append);
    g.RotateTransform(_angle); // do the rotation
    // make sure the centre of the rectangle is the centre of rotation (0, 0)
    g.FillRectangle(new SolidBrush(Color.Red), -5, -5, 10, 10);
}

答案 1 :(得分:0)

在我看到@ steve16351的回复之前我已经弄明白了,但他的代码仍然有用。我所做的是从使用PointF切换到Rectangle,因为Rectangle有一个属性,它保存左上角的坐标值,所以我可以在游戏循环中以稳定的速率增加/减少它让它旋转。