获取具有由鼠标位置定义的坐标的线

Getting a line that has the coordinates defined by the mouse location

我正在尝试制作一个小图形程序,它在屏幕上有一个直径为 100 的圆,从它的中心开始,有一条线一直连接到鼠标指针,直到那时用户单击,然后永久绘制该线。和MSPaint的线一模一样,只不过起点永远是圆心

我尝试了一些无效的方法。

  1. 我只能在单击鼠标后显示该行。那不是我想要的。我希望这条线始终存在并从圆心旋转直到单击鼠标,然后它就会永久显示在屏幕上。

  2. 我可以得到一个总是画线的脏东西。它形成了一种星形,但这也不是我想要的。

基本上,我想要的功能与您在 MSPaint 中绘制线条时的功能相同。我应该做些什么?画线过一秒擦掉,等鼠标在新的位置再画?我试过类似的方法,但它会稍微擦除背景,然后仅在鼠标移动时才绘制线条,但在鼠标静止时不绘制。

如果有人能提供代码片段,那就太好了。或者只是一些伪代码。

这是正确的伪代码吗? 开始: 单击鼠标左键,从圆心到鼠标尖端出现一条线 线一直停留在那里,直到创建新的鼠标坐标(我如何跟踪)? 从圆心到原始位置的线被擦除 新行是到鼠标坐标的新位置。

我认为这是一个状态机,可以使用我在数字领域学到的知识 class。 C# 中的状态是如何实现的?

任何帮助将不胜感激,感谢所有能理解我的问题的人,即使我可能没有使用正确的术语。

简短的回答是您需要一些定制绘画。较长的答案涉及自定义绘图和事件处理。

您需要的另一段代码是用于保存所有行的某种列表。下面的代码创建一个用户控件并在不依赖状态机的情况下进行自定义绘制。要对其进行测试,请创建一个新项目并添加一个名为 UserControl1 的用户控件,并将其添加到窗体中。确保您参与列出的活动。

我试图评论相关部分,这显示了一种快速而肮脏的方式来做你似乎想做的事情。

using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace CustomDrawingAndEvents
{
public partial class UserControl1 : UserControl
{
    private struct MyLine
    {
        public Point mStart;
        public Point mEnd;
        public MyLine(Point xStart, Point xEnd)
        {
            mStart = xStart;
            mEnd = xEnd;
        }
    }

    private List<MyLine> mLines;
    private Point mCircleCenter;
    private Point mMousePosition;

    public UserControl1()
    {
        InitializeComponent();
        mLines = new List<MyLine>();

        //Double Buffer to prevent flicker
        DoubleBuffered = true;
        //Create the center for our circle. For this just put it in the center of 
        //the control.
        mCircleCenter = new Point(this.Width / 2, this.Height / 2);
    }

    private void UserControl1_MouseClick(object sender, MouseEventArgs e)
    {
        //User clicked create a new line to add to the list.
        mLines.Add(new MyLine(mCircleCenter, e.Location));
    }

    private void UserControl1_MouseMove(object sender, MouseEventArgs e)
    {
        //Update mouse position
        mMousePosition = e.Location;
        //Make the control redraw itself
        Invalidate();
    }

    private void UserControl1_Paint(object sender, PaintEventArgs e)
    {
        //Create the rect with 100 width/height (subtract half the diameter to center the rect over the circle)
        Rectangle lCenterRect = new Rectangle(mCircleCenter.X - 50, mCircleCenter.Y - 50, 100, 100);

        //Draw our circle in the center of the control with a diameter of 100 
        e.Graphics.DrawEllipse(new Pen(Brushes.Black), lCenterRect);

        //Draw all of our saved lines
        foreach (MyLine lLine in mLines) 
            e.Graphics.DrawLine(new Pen(Brushes.Red), lLine.mStart, lLine.mEnd);            

        //Draw our active line from the center of the circle to
        //our mouse location
        e.Graphics.DrawLine(new Pen(Brushes.Blue), mCircleCenter, mMousePosition);
    }
}

}