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

Cannot clear custom control in OnPaint method

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

如何在重绘之前清除控件?

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

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