绘制可点击的线条和形状

时间:2019-08-13 16:43:09

标签: c# winforms

我有一个txt文件中的行列表,C#程序需要从txt文件中收集数据并从txt文件中绘制每一行。我需要使它们以某种方式可单击,因此,如果我单击一行,程序将识别出是哪个特定的行对象,并且可以选择删除它并重新绘制没有该行的图像(并重复此操作,直到我只有一行为止)需要)

我只是不确定如何使这种情况发生,我应该为可点击的绘图部分使用哪种技术。

我尝试使用winform,因为它似乎很适合画布和显示,绘制功能等工作。我制作了一些类,用于使用小型层次系统存储txt中的数据。在顶部有一个图像类,它有一个Shape列表(程序仅处理1张图像,但是该图像可以包含更多形状,有些包含在另一个形状中),Shape类具有Line列表,Line类具有int变量: fromX,fromY,toX,toY 我能够从txt中获取所有数据并将其加载到程序中,然后将一些数据写到控制台中,它们已经正确存储,我可以从Image对象中获取每一行的坐标。现在,我需要一个接一个地绘制每个线对象,并使它们可单击(可能是一个onclick事件,它返回或存储单击线的数据),但是我卡住的部分是我不知道该怎么办计算单击是否在一行上,如果单击在一行上,那么该行对象是要获取正确数据的那个行对象。

/*
Example of input file (two triangle and one pentagon on the pic, lines with ? are shape dividers)

X:Y>X:Y
810:-448>935:-532
935:-532>806:-534
806:-534>804:-449
?:?>?:?
597:-529>673:-411
673:-411>747:-531
747:-531>597:-529
?:?>?:?
475:-275>582:-355
582:-355>541:-487
541:-487>411:-487
411:-487>370:-355
370:-355>475:-275
?:?>?:?
*/

//As I mentioned I stored the data in line objects
class Line
    {
        public int startX;
        public int startY;
        public int endX;
        public int endY;

        public Line(int startX, int startY, int endX, int endY)
        {
            this.startX = startX;
            this.startY = startY;
            this.endX = endX;
            this.endY = endY;
        }

    }

//Every shape is an object with a list of the Line objects
 class Shape
    {
        public List<Line> lines = new List<Line>();

        public void AddLine(Line a)
        {
            this.lines.Add(a);
        }

        public void RemoveLine(Line a)
        {
            this.lines.Remove(a);
        }

        public void ResetShape()
        {
            this.lines.Clear();
        }

        public Line GetLine(int index)
        {
            return this.lines[index];
        }
    }

//Image class looks similar, it has a List of Shapes, the main difference is the constructor.
//The constructor get the file path as parameter, opens it, read and store data
//Split every line, get the coordinates, make line objects and add them to a temp Shape object's list
//When the read reach a divider it adds the temp Shape object to the Image's shape list
//Then reset the temp Shape object and continue to collect new lines untile the file reach the last line (which is a divider) 

1 个答案:

答案 0 :(得分:0)

尝试使用继承。控件类型(System.Windows.Forms.Control)具有Click方法(还有更多的鼠标和键盘事件)

public class Shape : Control
{

}

然后,当您想向其添加click事件时,只需使用:

private void SomeMethod()
{
    Shape shape = new Shape();
    shape.Click += Shape_Click;
}

private void Shape_Click(object sender, System.EventArgs e)
{
    // Do Something
}

如果要使其更短,可以使用以下方法:

Shape shape = new Shape();
shape.Click += (object sender, System.EventArgs e) =>
{
    // Do Something
};

做同样的事情。

祝你好运!