无法在OnPaint方法中清除自定义控件

时间:2016-01-13 15:57:56

标签: c# winforms c#-2.0

我有一个自定义控件,其功能是显示由外部库创建的图像。我已经通过重载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方法并自己重绘背景。其中没有一个有任何影响。

在重绘之前,我该怎样做才能清除我的控制?

1 个答案:

答案 0 :(得分:0)

可能发生的事情是,只有部分控件被无效,因此只有部分内容被重新绘制。要解决此问题,请添加Resize事件处理程序并在其中调用Invalidate()以使整个控件无效并强制完全重新绘制。

编辑:在问题的评论中,@ LarsTech建议设置ResizeRedraw,这是我以前从未注意到的。与我建议的Resize事件处理程序相比,这看起来更清晰,更符合库的设计。