如何在绘画事件中保留以前的图形
本文关键字:图形 保留 绘画 事件 | 更新日期: 2023-09-27 18:34:24
我正在使用
e.Graphics.FillEllipse(Brushes.Red, ph1.X,ph1.Y, 20, 20);
在panel1_Paint
事件中绘制一个椭圆。值ph1
点来自textbox_KeyPress
。
我还在textbox_KeyPress事件中添加了panel1.Invalidate();
以强制重绘panel1
。 它正在做的是清除面板1,然后添加新图形。
我真正希望它做的是在不清除以前的图形的情况下添加新图形。
有没有办法?
最简单的
方法是创建一个有序的对象集合(例如<>List),每次调用 OnPaint 事件时都会重绘该集合。
像这样:
// Your painting class. Only contains X and Y but could easily be expanded
// to contain color and size info as well as drawing object type.
class MyPaintingObject
{
public int X { get; set; }
public int Y { get; set; }
}
// The class-level collection of painting objects to repaint with each invalidate call
private List<MyPaintingObject> _paintingObjects = new List<MyPaintingObject>();
// The UI which adds a new drawing object and calls invalidate
private void button1_Click(object sender, EventArgs e)
{
// Hardcoded values 10 & 15 - replace with user-entered data
_paintingObjects.Add(new MyPaintingObject{X=10, Y=15});
panel1.Invalidate();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// loop through List<> and paint each object
foreach (var mpo in _paintingObjects)
e.Graphics.FillEllipse(Brushes.Red, mpo.X, mpo.Y, 20, 20);
}