如何让我的 Windows Forms drawn 用户控件在不裁剪的情况下调整得更大?

How do I get my Windows Forms drawn user control to resize larger without clipping?

我正在使用 VB.NET 在 Windows Forms 应用程序中创建自己的用户控件,并使其大小随包含它的表单一起变化。只要 window 大小保持不变并且控件保持在其原始范围内,它看起来就没问题。但是,如果我调整 window 的大小以使其变大,控件的内容将随之调整大小,但最终会被裁剪为原始大小。我不确定这是从哪里来的,到目前为止还没有找到任何方法来修复它。

下面是一些用户控件的快速示例代码,可以重现我遇到的问题:

TheCircle.vb:

Public Class TheCircle
    Private _graphics As Graphics

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        _graphics = CreateGraphics()
        SetStyle(ControlStyles.ResizeRedraw, True)
        BackColor = Color.Red
    End Sub

    Private Sub TheCircle_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        _graphics.FillRectangle(Brushes.Blue, ClientRectangle)
        _graphics.FillEllipse(Brushes.LimeGreen, ClientRectangle)
    End Sub
End Class

然后我在主窗体中重建项目后放置此用户控件并将其停靠或锚定(结果相同,但后者有助于更好地显示裁剪问题所在)。下面是我尝试将控件调整到超出 "default" 大小时的结果截图:

绿色椭圆和蓝色 "background" 矩形应该占据整个控制区域,但它们不是(它被剪裁,您看到的是红色 BackColor)。虽然当控件处于原始大小或更小时,它看起来像预期的那样运行。我怎样才能解决这个问题?我是 GDI+ 的新手,所以我确定它一定就在我眼皮底下...

这是不必要的,而且通常是个坏主意:_graphics = CreateGraphics()

不好是因为它易变。你得到一个一次性的图形对象,用它画一些东西,然后下一个刷新周期,除非你继续这样做,否则它就会丢失。

正确的方法是使用 Paint 事件,因为它在 PaintEventArgs 中为您提供 Graphics 对象,并且每次需要重新绘制时都会调用它.您可以通过调用 theCircle.Invalidate()(或 Refresh() 以获得更直接的重绘)在代码中的任何位置请求重绘。

Public Class TheCircle

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        SetStyle(ControlStyles.ResizeRedraw, True)
        BackColor = Color.Red
    End Sub

    Private Sub TheCircle_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        e.Graphics.FillRectangle(Brushes.Blue, ClientRectangle)
        e.Graphics.FillEllipse(Brushes.LimeGreen, ClientRectangle)
    End Sub
End Class