我在VB.NET Winforms上有一个RichTextBox,我希望它在Liberation Mono 10pt字体中显示(比方说)12行文本。我当然可以手动调整大小,但我想根据字体大小和行数以编程方式调整大小。我正在努力解决的问题是如何计算出一条线的高度。我试过了:
RichTextBox.Height = RichTextBox.Font.Height
和
RichTextBox.Height = RichTextBox.Font.GetHeight
但似乎都没有给我我想要的确切尺寸。有没有办法测量RTB中线的确切高度?
谢谢@Arman,我最终做到了这一点:
Public Function GetHeightOfFirstNumLines(ByVal RTB As RichTextBox, ByVal NumLines As Integer) As Integer
Dim Position1 = RTB.GetPositionFromCharIndex(RTB.GetFirstCharIndexFromLine(0))
Dim Position2 = RTB.GetPositionFromCharIndex(RTB.GetFirstCharIndexFromLine(NumLines))
Return Position2.Y - Position1.Y
End Function
然后在Form.Load事件中,此代码:
Dim RTBSize As New Size(TextRenderer.MeasureText("M", MemoryRtb.Font, MemoryRtb.Size, TextFormatFlags.WordBreak))
MemoryRtb.ClientSize = New Size(MemoryRtb.ClientSize.Width, (RTBSize.Height * 11) + 5)
答案 0 :(得分:1)
线条可以有不同的高度,所以你可以这样做:
Private Shared Function GetHeightOfFirstLines(ByVal Rtb As RichTextBox, ByVal NumLines As Integer) As Integer
Dim p1 = Rtb.GetPositionFromCharIndex(Rtb.GetFirstCharIndexFromLine(0))
Dim p2 = Rtb.GetPositionFromCharIndex(Rtb.GetFirstCharIndexFromLine(NumLines))
Return p2.Y - p1.Y
End Function
然后
RichTextBox1.ClientSize = New Size(RichTextBox1.ClientSize.Width, GetHeightOfFirstLines(RichTextBox1, 10))
但是,这要求您在文本框中已经有10行文本。如果你没有,你可以得到第一行的高度,并假设未来十行的高度相同:
RichTextBox1.ClientSize = New Size(RichTextBox1.ClientSize.Width, GetHeightOfFirstLines(RichTextBox1, 1) * 10)
答案 1 :(得分:1)
使用TextRenderer.MeasureText()
Dim rtbSize As New Size(TextRenderer.MeasureText(RichTextBox1.Text, RichTextBox1.Font, RichTextBox1.Size, TextFormatFlags.WordBreak))
RichTextBox1.Height = rtbSize.Height + 10