'获取在指定宽度内,可容纳的指定字体字符串最长子字符串
'参数说明: Text 测量字符串,printFont 使用字体,Length 截取的打印长度
'函数返回: 截取所得子字符串
'Added By Canny, 2003.7.22
'Modified, 2003.8.6
Private Function GetFitText(ByVal Text As String, ByVal printFont As Font, ByVal Length As Single) As String
Dim sngWidth As Single '字符串宽度
Dim intCharCnt As Integer = Text.Length '字符个数
Dim intTmp As Integer '保存上次尝试字符个数
Dim g As System.Drawing.Graphics
Text &= Space(255) 'Text长度不足时,以空格填充
g = (New System.Windows.Forms.Panel()).CreateGraphics
'每次测量时,添加一个非空白字符,使测量包含右边空格宽度
'添加非空白字符后的宽度增量
Dim addWidth As Single = g.MeasureString("ll", printFont).Width - g.MeasureString("l", printFont).Width
If intCharCnt > Text.Length Then '若给定字符串长度小于可容纳长度,直接返回给定字符串
Text &= Space(255) 'Text长度不足时,以空格填充
End If
'计算尝试字符串的打印宽度
sngWidth = g.MeasureString(Text.Substring(0, intCharCnt) & "l", printFont).Width - addWidth
If sngWidth > Length Then '若尝试字符串打印宽度大于可容纳长度,
Select Case intCharCnt - intTmp
Case 1
'并且尝试字符数比原字符数多1,则取原字符数
'原字符串打印宽度小于可容纳长度,多加一个字符后,打印宽度大于可容纳长度
intCharCnt = intTmp
Exit Do
Case 0
'并且尝试字符数与原字符数相等,减少一个字符重试
intCharCnt -= 1
End Select
End If
Loop Until intTmp = intCharCnt