我一直在研究一个简单的图形项目,可以在其中使用按钮绘制形状并进行编辑(调整大小和其他内容)。我已经能够绘制不同的形状,但是我的问题是我无法再次绘制相同的形状。只会更新以前相同形状的参数。
例如,我尝试绘制一个矩形,然后我想再次绘制一个不同的大小,该矩形会更改其大小,而不是创建一个新的矩形。
这是我的代码:
形状类别
Y
绘画班
class ShapeClass
{
public int x { get; set; }
public int y { get; set; }
public int width { get; set; }
public int height { get; set; }
public Pen color { get; set; }
public string Shape { get; set; }
}
绘画活动
class Draw:ShapeClass
{
public void DrawRectangle(PaintEventArgs e)
{
e.Graphics.DrawRectangle(color, new Rectangle(x, y, width, height));
}
public void DrawSquare(PaintEventArgs e)
{
e.Graphics.DrawRectangle(color, new Rectangle(x, y, width, height));
}
public void DrawCircle(PaintEventArgs e)
{
e.Graphics.DrawEllipse(color, new Rectangle(x,y,width,height));
}
public void DrawEllipse(PaintEventArgs e)
{
e.Graphics.DrawEllipse(color, new Rectangle(x, y, width, height));
}
答案 0 :(得分:0)
让我们看一下您的PaintCircle
事件处理程序:
public void PaintCircle(object sender, PaintEventArgs e)
{
//Calls Draw class and sets the parameters of the Shape.
Draw d = new Draw();
d.x = cX;
d.y = cY;
d.width = cW;
d.height = cH;
d.color = new Pen(Color.Red, 2);
d.DrawCircle(e);
}
挺直截了当的,但是看起来非常像您在表单上cX
,cY
,cW
和{{1} }。其他cH
方法中也有类似的变量。
几乎可以肯定,您正在调整这些变量并重新绘制画布。通常,这将擦除现有内容并完全重绘,这意味着您的现有图像将被删除,而“新”形状将被绘制。
有两种方法可以解决此问题:
您可以根据画布的形状创建一个Paint...
对象,在System.Drawing.Bitmap
上绘制所有图形,然后更新显示。
这样做的缺点是您无法返回并更改现有对象。在图像上绘制后,图像将永久更改为新形状。
如果您采用这种方式,则可能应该考虑使用多个Bitmap
图像,以便可以通过从列表中取出先前的图像来撤消操作。开始绘制操作时,请复制当前的Bitmap
并将副本放入撤消列表中。要撤消操作,请从该列表中拉出最后一项,并用它来代替工作的Bitmap
。不要忘记整理您的撤消列表,以确保您不使用所有内存。
为此,您将需要构建一些更有趣的Bitmap
类。
这里是一个快速示例...
Shape
...等等。
您可以在主表单上添加一个public abstract class Shape
{
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public Pen LineColor { get; set; } = Pens.Red;
public Brush FillColor { get; set; } = null;
public abstract void Draw(Graphics g);
}
public class EllipseShape : Shape
{
public override void Draw(Graphics g)
{
if (FillColor != null)
g.FillEllipse(FillColor, X, Y, Width, Height);
g.DrawEllipse(LineColor, X, Y, Width, Height);
}
}
public class RectangleShape : Shape
{
public override void Draw(Graphics g)
{
if (FillColor != null)
g.FillRectangle(FillColor, X, Y, Width, Height);
g.DrawRectangle(LineColor, X, Y, Width, Height);
}
}
来保存形状,然后在画布的List<Shape>
事件中-使用任何类型的画布-您都可以这样做:
OnPaint