我正在使用VB.NET在Windows窗体应用程序中创建自己的用户控件,并将其大小与包含它的表单一起更改。只要窗口大小保持不变并且控件保持在其原始范围内,它看起来就可以了。但是,如果我调整窗口大小以使其变大,控件的内容将随之调整大小,但最终会以原始大小剪裁。我不确定这是从哪里来的,到目前为止还没有找到任何办法解决它。
下面是一些用户控件的快速示例代码,可以重现我遇到的问题:
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
然后我在我的主窗体中重建项目之后放置此用户控件,并将其停靠或锚定它(相同的结果,但后者有助于更好地显示剪切问题的位置)。下面是我尝试将控件的大小调整到超出其“默认”大小时的结果的屏幕截图:
绿色椭圆和蓝色“背景”矩形应该占据整个控制区域,但它们不是(它被裁剪,而是看到红色BackColor
)。当控件处于原始大小或更小时,它看起来像预期的那样。我怎样才能解决这个问题?我对GDI +很新,所以我确信它一定是在我的鼻子底下......
答案 0 :(得分:1)
这是不必要的,而且通常是个坏主意:_graphics = CreateGraphics()
这很糟糕,因为它很不稳定。你得到一个一次性的图形对象,用它绘制一些东西,然后是下一个刷新周期,它会丢失,除非你继续这样做。
正确的方法是使用Paint
事件,因为它在Graphics
中为您提供PaintEventArgs
对象,并且每次需要重新绘制时都会调用它。您可以致电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