我正在使用
e.Graphics.FillEllipse(Brushes.Red, ph1.X,ph1.Y, 20, 20);
在panel1_Paint
事件中绘制椭圆。点ph1
值来自textbox_KeyPress
。
我还在textbox_KeyPress事件中添加了panel1.Invalidate();
以强制重绘panel1
。它正在做的是清除panel1然后添加新图形。
我真正希望它做的是添加新图形而不清除以前的图形。
是否有方法?
答案 0 :(得分:2)
最简单的方法是创建一个有序的对象集合(例如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);
}