想要在C#中使用绘制的圆圈跟随我的鼠标

cks*_*ubs 4 c# winforms

首先,我是C#真正的初学者,所以请保持温柔.

我正试图跟着我的光标圈.我不希望任何"小道"落在后面.

private void Form1_MouseMove(object sender, MouseEventArgs e)
{

    drawCircle(e.X, e.Y);

}

private void drawCircle(int x, int y)
{
    Pen skyBluePen = new Pen(Brushes.DeepSkyBlue);
    Graphics graphics = CreateGraphics();
    graphics.DrawEllipse(
        skyBluePen, x - 150, y - 150, 300, 300);
    graphics.Dispose();
    this.Invalidate();
}
Run Code Online (Sandbox Code Playgroud)

这可以正常工作,因为它绘制它并以鼠标为中心进行每次鼠标移动.但是,"this.Invalidate();" 是错的.它在每次运动后"拉出"形状,所以我只能看到它的一瞥.但是,不包括它会导致每个绘制的圆圈保留在屏幕上.

我如何让一个圆圈"优雅地"跟随我的鼠标,而不是太过于跳跃而没有保留所有过去的圆圈?

Eri*_*bal 14

你可以这样做:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Point local = this.PointToClient(Cursor.Position);
        e.Graphics.DrawEllipse(Pens.Red, local.X-25, local.Y-25, 20, 20);
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        Invalidate();
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,在鼠标移动时,无效.在画上,画出你的圆圈.

  • 你可以添加"this.DoubleBuffered = true;" 作为ctor的一部分,它也可能有助于一些闪烁. (2认同)