如何实现DrawLine绕圆周旋转动画?用Timer实现无轨迹持续旋转
使用Timer实现直线绕圆心无间断旋转动画
实现步骤
添加Timer控件:在窗体上放置一个
Timer,设置Interval(比如20,值越小旋转越快),将Enabled设为true。定义全局变量:在窗体类中声明以下变量,用于存储旋转状态和基础参数:
private float _currentAngle = 0f; private float _lineLength = 100f; // 自定义直线长度 private PointF _centerPoint;
- 更新圆心坐标:监听窗体加载和PictureBox尺寸变化事件,确保圆心始终在控件中心:
private void Form1_Load(object sender, EventArgs e) { UpdateCenter(); } private void pictureBox1_SizeChanged(object sender, EventArgs e) { UpdateCenter(); } private void UpdateCenter() { _centerPoint = new PointF( pictureBox1.ClientSize.Width / 2f, pictureBox1.ClientSize.Height / 2f ); }
- 重构DrawLine方法:根据角度计算直线终点,用三角函数实现旋转逻辑,同时优化资源释放:
public void DrawLine(PictureBox pb, Graphics g, float angle) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; // 弧度转换 + 终点坐标计算 float radian = angle * (float)Math.PI / 180; float endX = _centerPoint.X + _lineLength * (float)Math.Cos(radian); float endY = _centerPoint.Y + _lineLength * (float)Math.Sin(radian); using (Pen redPen = new Pen(Color.Red, 2f)) { g.DrawLine(redPen, _centerPoint, new PointF(endX, endY)); } }
- Timer Tick事件处理:更新角度并触发重绘,实现连续旋转:
private void timer1_Tick(object sender, EventArgs e) { _currentAngle += 2f; // 每次旋转2度,可调整速度 if (_currentAngle >= 360f) _currentAngle = 0f; // 重置角度避免溢出 pictureBox1.Invalidate(); // 触发重绘,自动清除旧轨迹 }
- 修改Paint事件:传入当前角度绘制旋转后的直线:
private void pictureBox1_Paint(object sender, PaintEventArgs e) { DrawLine(pictureBox1, e.Graphics, _currentAngle); }
效果说明
每次Timer触发时,角度更新并调用Invalidate(),PictureBox会自动刷新背景清除之前的直线,然后绘制当前角度的新直线,从而实现无间断旋转且无轨迹残留的效果。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

