vb.net固定长度的label根据显示文字的多少自动放大/缩小字体

前提:画面得放一个隐藏的Label,并且该隐藏Label的【AutoSize】属性设置为【TRUE】。

调用方法:
SetFontSize(Me.lbl13, Me.lblArari, 152, 22, “” & Format(result, “###,##0”))
参数说明:lbl13 –画面隐藏Label。
lblArari –要改变字体大小的目标Label。
152 –要改变字体大小的目标Label的最大宽度。
22 –要改变字体大小的目标Label的最大字体大小。
“” & Format(result, “###,##0”) —-要改变字体大小的目标Label的text

Private Sub SetFontSize(ByVal lblCompare As Label,
                        ByVal lblResult As Label,
                        ByVal lblWidth As Single,
                        ByVal lblFontSize As Single,
                        ByVal txtResult As String)
    Dim lblFont As Font = New Font(lblResult.Font.FontFamily, lblFontSize, lblResult.Font.Style)
    lblCompare.Text = txtResult

    If lblCompare.Width <= lblResult.Width Then
        lblResult.Width = lblWidth
        lblResult.Font = lblFont
        lblResult.Text = txtResult
    Else
        Dim iChangeFontSize As Single = lblFontSize
        SetFontSizeChange(iChangeFontSize, lblCompare, lblResult, lblWidth, lblFontSize, txtResult)
    End If
End Sub

Private Function SetFontSizeChange(ByRef iChangeFontSize As Single,
                                   ByVal lblCompare As Label,
                                   ByVal lblResult As Label,
                                   ByVal lblWidth As Single,
                                   ByVal lblFontSize As Single,
                                   ByVal txtResult As String) As Boolean

    Dim lblFont As Font = New Font(lblResult.Font.FontFamily, iChangeFontSize, lblResult.Font.Style)

    If iChangeFontSize < 1 OrElse iChangeFontSize - 0.25 < 1 Then
        lblResult.Font = lblFont
        lblResult.Text = txtResult
        Return True
    End If

    iChangeFontSize += -0.25
    lblCompare.Font = lblFont

    If lblCompare.Width > lblResult.Width Then
        If SetFontSizeChange(iChangeFontSize, lblCompare, lblResult, lblWidth, lblFontSize, txtResult) = True Then
            Return True
        End If
    End If
    lblResult.Font = lblFont
    lblResult.Text = txtResult
    lblCompare.Font = New Font(lblResult.Font.FontFamily, lblFontSize, lblResult.Font.Style)
    Return True
End Function
    原文作者:Vera_Wangs
    原文地址: https://blog.csdn.net/Vera_Wangs/article/details/118224002
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞