【发布时间】:2016-01-13 15:57:55
【问题描述】:
我有一个自定义控件,其功能是显示由外部库创建的图像。我通过重载 OnPaint 函数、在那里生成和绘制图像来实现这一点。
我的问题是,当我的控件大小发生变化并且重新创建和绘制图像时,旧图像仍然可见。
我的 OnPaint 方法相对简单,因为图像创建是在它自己的方法中:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (image == null || this.Width != image.Width || this.Height != image.Height)
{
// Remove the old image so we don't accidentally draw it later.
this.image = null;
// Attempt to clear the control.
//e.Graphics.Clear(this.BackColor);
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), 0, 0, this.Width, this.Height);
try
{
this.Plot(); // Create my image from the library based on current size.
}
catch (Exception ex)
{
SizeF size = e.Graphics.MeasureString(ex.Message, this.Font);
e.Graphics.DrawString(ex.Message, this.Font, Brushes.Black, (this.Width - size.Width) / 2, (this.Height - size.Height) / 2);
}
}
if (this.image != null)
e.Graphics.DrawImageUnscaled(image, 0, 0);
}
如您所见,我尝试了一些方法来清除控件,包括 Graphics.Clear 方法和自己重绘背景。这些都没有任何效果。
在重绘之前我可以做些什么来清除我的控制?
【问题讨论】:
-
绘制前调用this.invalidate有效吗?
-
好吧,我试图避免在 OnPaint 中调用它,因为据我所知,它无效会导致重绘,所以我认为这会产生无限循环。 adv12 关于调整大小无效的建议不仅解决了这个问题,而且解决了问题(我现在接受答案还为时过早)
-
你是对的......有一段时间没有在winforms上工作了,但是adv12的回答很好。 :]
-
将 FillRectangle 调用移到 if 条件之前。在控件的构造函数中,设置 ResizeRedraw = true 和 DoubleBuffered = true。
-
OnPaintBackground() 的工作是确保您在“干净”的背景上绘画。您继承的默认设置使用 BackColor 属性填充控件。很不清楚发生了什么。如果您从容器控件(如 Panel)继承,则需要 ResizeRedraw。