我有一个 Windows 窗体应用程序,可以在其中向主窗体添加不同的图形(矩形、圆形等)。该图是一个用户控件,它是我用 GraphicsPath 定义的形状。添加新图的方法:
void AddElement(ShapeType shape, string guid)
{
Shape newShape = new Shape();
newShape.Name = guid;
newShape.Size = new Size(100, 100);
newShape.Type = shape;
newShape.Location = new Point(100, 100);
newShape.MouseDown += new MouseEventHandler(Shape_MouseDown);
newShape.MouseMove += new MouseEventHandler(Shape_MouseMove);
newShape.MouseUp += new MouseEventHandler(Shape_MouseUp);
newShape.BackColor = this.BackColor;
this.Controls.Add(newShape);
}
在形状(图)类中:
private ShapeType shape;
private GraphicsPath path = null;
public ShapeType Type
{
get { return shape; }
set
{
shape = value;
DrawElement();
}
}
private void DrawElement()
{
path = new GraphicsPath();
switch (shape)
{
case ShapeType.Rectangle:
path.AddRectangle(this.ClientRectangle);
break;
case ShapeType.Circle:
path.AddEllipse(this.ClientRectangle);
break;
case ShapeType.Line:
path.AddLine(10,10,20,20);
break;
}
this.Region = new Region(path);
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
if (path != null)
{
e.Graphics.DrawPath(new Pen(Color.Black, 4), path);
}
}
调整图形大小时,我重绘它:
protected override void OnResize(System.EventArgs e)
{
DrawElement();
this.Invalidate();
}
当我添加矩形和圆形等形状时,一切正常。但是当我选择 Line 时,我的表单上什么也没有出现。断点表明程序在所有方法中都执行了步骤this.Controls.Add(newShape);
。
我不明白为什么这不起作用。我会很感激任何建议。