winforms 如何动画绘制线移动在一个圆圈?

j2cgzkjk  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(124)

使用计时器,我希望线在一个圆圈不间断地旋转。

public void DrawLine(PictureBox pb, Graphics g, float angle)
{
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    g.DrawLine(new Pen(Color.Red, 2f), new Point(pictureBox1.ClientSize.Width / 2, pictureBox1.ClientSize.Height / 2), new Point((int)w,(int)h));
}

在绘画中

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    DrawLine(pictureBox1, e.Graphics, 0);
}

相反,静态画线,使线在周围的圆圈,而不留下线后,只是单一的画线。

zaq34kh6

zaq34kh61#

你必须定义一个变量double angle,然后每毫秒增加一个量,然后只需将半径lengight乘以sin和余弦的than angle:

//using System.Timers;

public void DrawLine(PictureBox pb, Graphics g, float angle)
{
    double radius = pictureBox1.ClientSize.Width / 2;
    var center = new Point(radius, radius);
    // remember that sin(0)=0 and cos(0)=1
    // so if angle==0 the line is pointing up
    // EDIT HERE: added center.x and center.y 
    var end = new Point(center.X + radius * Math.sin(angle), center.Y + radius * Math.cos(angle));
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    g.DrawLine(new Pen(Color.Red, 2f), center, end);
}
public static void rotate(Object source, ElapsedEventArgs e)
{
    angle += <someAmountInRadiants>;
}
public static void SetTimer()
{
    rotationTimer.Elapsed += rotate;
    ...  // *for the uses of timers see below
}
double angle = 0;
Timer rotationTimer = new(<someAmountInMilliseconds>);
setTimer();

要使用总旋转时间和步数来确定旋转速度,您可以使用Math.PI

# seconds needed to complete a full rotation
double rotTime = 2; # what you want

# how many times per second the line get mooved
double rotSteps = 360; # what you want

# amount of rotation that the line has to do, we can use this variable in rotate()
double rotAmount = Math.PI / rotSteps; 

# every how much time increment the angle?
double rotDelay = rotTime / rotSteps; 

# we use this in the timer, so we need to convert from seconds to milliseconds
rotDelay *= 1000;

相关问题