好的,所以...我正在尝试创建一个自定义复选框,该复选框实际上根据字体大小调整字形的大小(请转到 MS,因为它永远不会实现此功能)。为了正确执行此操作,我必须完全覆盖控件中的 OnPaint 事件。但是,当控件设置为透明时,我遇到了问题。
当父控件(我现在只做一层透明度)没有边框(特别是设置为 FormBorderStyle = None 的窗口窗体时,它工作得很好。但是,如果我将它设置为除此之外的任何东西,坐标关闭并抓住我的位图的错误部分。我在代码下方发布了屏幕截图的链接以演示差异。我无法弄清楚为什么它不能正确定位边框。我认为它与客户端尺寸有关,但可以'不正确。此外,使用'drawtobitmap'函数,OnPaint 会大量递归自身,并减慢绘制控件的速度,有没有办法阻止它?
这是相关代码
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
OnPaintBackground(e)
If MyBase.Appearance = Appearance.Button Then
MyBase.OnPaint(e)
Else
End If
End Sub
Protected Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
If BackColor = Color.Transparent Then
Dim ctl As Control = Parent
Dim bmp As New Bitmap(ctl.ClientSize.Width, ctl.ClientSize.Height)
ctl.DrawToBitmap(bmp, New Rectangle(0, 0, ctl.ClientSize.Width, ctl.ClientSize.Height))
Dim rect As New Rectangle((ctl.Size.Width - ctl.ClientSize.Width) + Left, (ctl.Size.Height - ctl.ClientSize.Height) + Top, ClientSize.Width, ClientSize.Height)
e.Graphics.FillRectangle(New TextureBrush(CropImage(bmp, rect)), ClientRectangle)
ctl.Text = ((ctl.Size.Width - ctl.ClientSize.Width) + Left).ToString + " " + ((ctl.Size.Height - ctl.ClientSize.Height) + Top).ToString + " " + ClientSize.Width.ToString + " " + ClientSize.Height.ToString
bmp.Dispose()
Else
e.Graphics.FillRectangle(New SolidBrush(MyBase.BackColor), ClientRectangle)
End If
End Sub
Private Function CropImage(ByVal source As Image, ByVal crop As Rectangle) As Bitmap
Dim bmp = New Bitmap(crop.Width, crop.Height)
Using gr = Graphics.FromImage(bmp)
gr.DrawImage(source, New Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel)
End Using
Return bmp
End Function