我在C#中有绘制圆圈的代码:
Rectangle r = new Rectangle(300, 300, 50, 50);
g.FillEllipse(brush, r);
我在c#中遇到旋转圆问题。
我有一个像汽车轮胎一样的圆圈,我想向前旋转。就像那样:
答案 0 :(得分:0)
试试这个,每个Graphics
对象都有一个名为RotateTransform
的方法,但是这只会绕着(0,0)旋转东西,我们必须将它与TranslateTransform
组合才能旋转任何点周围的东西(在这种情况下,该点应该是你的圆的中心点):
Rectangle r = new Rectangle(300, 300, 50, 50);
int dx = r.Left + r.Width/2;
int dy = r.Top + r.Height/2;
float alpha = 45;//rotate 45 degrees clockwise
g.TranslateTransform(dx, dy);
g.RotateTransform(alpha);
g.TranslateTransform(-dx,-dy);
g.FillEllipse(brush, r);
更新:我为你试过这个演示代码,它是一个从左边缘到右边缘的轮子,来回反转......我试图提高它的性能但它似乎是winforms
的限制,你可以看到车轮闪烁运行,启用DoubleBuffered
确实有点帮助,但不足以让它停止闪烁。亲自尝试一下。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
center = new PointF(startOffset+r, r + 30);
t.Interval = 1;
t.Tick += (se, e) =>
{
if (s >= ClientSize.Width - r*2 - startOffset) dir = -1;
else if (s <= startOffset) dir = 1;
center.X += dir * step;
Invalidate();
};
t.Start();
DoubleBuffered = true;
Paint += Form1_Paint;
}
Timer t = new Timer();
PointF center;
int r = 130;
float s;
float step = 1f;
int dir = 1;
int startOffset;
private void Form1_Paint(object sender, PaintEventArgs e)
{
s += step * dir;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Wheel(s, e.Graphics);
e.Graphics.FillEllipse(Brushes.Green,
new RectangleF(center.X - r, center.Y - r, r * 2, r * 2));
//draw this line to see how the wheel runs
e.Graphics.DrawLine(Pens.Red, new PointF(center.X - r, center.Y),
new PointF(center.X + r, center.Y));
}
public void Wheel(float dx, Graphics g)
{
float f = (float)(dx * 180 / (r * Math.PI));
g.TranslateTransform(center.X, center.Y);
g.RotateTransform(f);
g.TranslateTransform(-center.X, -center.Y);
}
}