问题描述
我创建了一个从Panel派生的自定义控件.我用它来显示一个使用BackgroundImage属性的图像.我重写OnClick方法并将isSelected设置为true,然后调用Invalidate方法并在重写的OnPaint中绘制一个矩形.一切正常,直到我将DoubleBuffered设置为true.绘制矩形,然后将其删除,我不知道为什么会发生这种情况.
I have created a custom control which derives from Panel. I use it to display an Image using BackgroundImage property. I override the OnClick method and set isSelected to true then call Invalidate method and draw a rectangle in overrided OnPaint.Everything goes just fine until I set DoubleBuffered to true. The rectangle is drawn and then it is erased and I can't get why this is happening.
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);
}
}
推荐答案
在您的PaintSelection
中,您不应创建新的Graphics
对象,因为该对象将绘制到前端缓冲区,然后该缓冲区立即被覆盖后台缓冲区的内容.
In your PaintSelection
, you should not create a new Graphics
object, because that object will draw to the front buffer, which is then promptly overdrawn by the contents of the back buffer.
将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);
}
}
这篇关于DoubleBuffered设置为true时覆盖OnPaint的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!