winforms 如何在本地报告中动态设置字体大小以适应文本框尺寸?

dgjrabp2  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(217)

如何在报表的文本框控件中动态设置字体大小,使文本框的内容适合其尺寸?我的想法是根据next函数的值在循环中减小字体大小:

Private Function IsContentsBiggerThanTextBox(ByVal textBox As TextBox) As Boolean
    Dim size As Size = TextRenderer.MeasureText(textBox.Text, textBox.Font)
    Return ((size.Width > textBox.Width)  OR (size.Height > textBox.Height))
End Function

问题是我不知道如何将报告文本框的引用传递给函数。

bxgwgixi

bxgwgixi1#

在多次尝试寻找在本地rdlc报告中工作的代码之后,我终于设法编写了在textbox控件中动态调整字体大小的函数,这取决于其中文本的大小。这个想法是测量文本框控件中的文本大小,如果我们发现文本高度高于文本框控件的高度,我们就减小字体的大小,直到文本适合控件。
首先,您必须在报表属性中添加对System.Drawing的引用。
rdlc报告中的所有代码都必须用vb.net编写。在报表属性的代码字段中添加以下函数:

'1cm = 37.79527559055 pixels
Const cmToPx as Single = 37.79527559055F

Public Function setMaxFont(Text as string, boxWidth as Single, boxHeight as 
Single, FontMax as Integer, FontMin as Integer) as String
    Dim i as Integer
    For i = FontMax to FontMin Step -1
        If IsTextSmaller(Text, i, boxWidth, boxHeight) Then
            Exit For
        End If
    Next
    return i & "pt"
End Function

Private Function IsTextSmaller(Text as String, fontValue as Integer, boxWidth as Single, boxHeight as Single) as Boolean
    Dim stringFont As New System.Drawing.Font("Arial", fontValue) 
    Dim stringSize As New System.Drawing.SizeF
    Dim boxSize as New System.Drawing.SizeF(boxWidth * cmToPx, boxHeight * cmToPx * 10) 'we set box height bigger than textbox that we check
    Dim bitmap as System.Drawing.Bitmap = New System.Drawing.Bitmap(1, 1)
    Dim g As  System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)
    g.PageUnit = System.Drawing.GraphicsUnit.Pixel
    stringSize = g.MeasureString(Text, stringFont, boxSize)
    bitmap = Nothing
    return stringSize.Height < (boxHeight * cmToPx)
End Function

选择要动态更改其字体大小的文本框控件,并在FontSize属性中添加以下代码:

= Code.SetMaxFont(TextBox.Value, WidthOfTextBox, HeightOfTextBox, MaxFontSize, MinFontSize)

文本框的宽度和高度必须输入厘米。文本框的CanGrow和CanShrink属性必须设置为False。

相关问题