我已经创建了一个从Panel派生的自定义控件。我使用它来使用BackgroundImage属性显示一个图像。我重写了OnClick方法并将isSelected设置为true,然后调用Invalidate方法并在重写的OnPaint中绘制一个矩形。在我将DoubleBuffered设置为true之前,一切都很顺利。这个矩形被画出来了,然后又被擦除了,我不明白为什么会这样。
public CustomControl()
: base()
{
base.DoubleBuffered = true;
base.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
PaintSelection();
}
private void PaintSelection()
{
if (isSelected)
{
Graphics graphics = CreateGraphics();
graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
}
}发布于 2010-07-15 20:12:37
在PaintSelection中,不应该创建新的Graphics对象,因为该对象将绘制到前台缓冲区,然后后台缓冲区的内容会立即透支前台缓冲区。
改为绘制在PaintEventArgs中传递的Graphics:
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
PaintSelection(pe.Graphics);
}
private void PaintSelection(Graphics graphics)
{
if (isSelected)
{
graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
}
}https://stackoverflow.com/questions/3255368
复制相似问题