如何在绘制事件中保留以前的图形? [英] How to retain previous graphics in paint event?
本文介绍了如何在绘制事件中保留以前的图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用
e.Graphics.FillEllipse(Brushes.Red, ph1.X,ph1.Y, 20, 20);
在panel1_Paint
事件中绘制一个椭圆.点 ph1
值来自 textbox_KeyPress
.
in the panel1_Paint
event to draw an ellipse. The point ph1
value comes from textbox_KeyPress
.
我还在 textbox_KeyPress 事件中添加了 panel1.Invalidate();
以强制在 panel1
上重绘.它正在做的是清除 panel1 然后添加新图形.
I also added panel1.Invalidate();
in the textbox_KeyPress event to force redraw on panel1
. What it is doing is clearing panel1 then add the new graphics.
我真正想让它做的是在不清除以前的图形的情况下添加新图形.
有什么方法吗?
推荐答案
最简单的方法是创建一个有序的对象集合(例如 List<>),每次调用 OnPaint 事件时都会重绘这些对象.
The simplest way is for you to create an ordered collection of objects (a List<> for example) which you would redraw each time that the OnPaint event is called.
类似于:
// 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);
}
这篇关于如何在绘制事件中保留以前的图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文