补充一些实现细节,以便评估TextRenderer的DrawText()方法和Graphics的DrawString()方法之间的差异。
单击表单后,两种方法在测量和呈现文本方面显示出它们的不同之处。
Dim sText As String() = New String() {
"C:\FirstLevelDir\FirstSubDir\AnotherDir\ADeepLevelDir\LostDeepDir\SomeFile.exe",
"C:\FirstLevelDir\AnotherFirstSubDir\AnotherGreatDir\AwsomeDeepLevelDir\LostDeepDir\Some.exe",
"C:\FirstLevelDir\SomeFirstSubDir\SomeOtherDir\AnotherDeepLevelDir\VeryLostDeepDir\FinalBuriedDir\SomeFile.exe"
}
在表单的
Click()
事件中,使用
TextRenderer.MeasureText() 测量
sText
行的宽度和高度,并使用
TextRenderer.DrawText() 打印它们。请保留 HTML 标签。
Private Sub Form1_Click(sender As Object, e As EventArgs) Handles Me.Click
Dim relPositionY As Integer = 0
Dim lineSpacing As Single = 0.5
Dim paragraphSpacing As Integer = CInt(Font.Height * lineSpacing)
Dim flags As TextFormatFlags = TextFormatFlags.Top Or
TextFormatFlags.WordBreak Or
TextFormatFlags.TextBoxControl
Using g As Graphics = CreateGraphics()
For x = 0 To sText.Length - 1
Dim textSize As Size = TextRenderer.MeasureText(
g, sText(x), Font,
New Size(ClientSize.Width, ClientSize.Height), flags
)
TextRenderer.DrawText(g, sText(x), Font,
New Rectangle(0, relPositionY, textSize.Width, textSize.Height),
ForeColor, flags)
relPositionY += textSize.Height + paragraphSpacing
Next
End Using
End Sub
在表单的
Paint()
事件中,使用
.Graphics.MeasureString() 测量
sText
行的宽度和高度,并用
.Graphics.DrawString() 打印它们。请注意,TextRenderer 中文本框的大小是相对于 Form.ClientSize 的,而在 Graphics 中是相对于 Form 的全宽度。
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
Dim relPositionY As Single = 0
Dim lineSpacing As Single = 0.5
Dim paragraphSpacing As Single = CSng(Font.Height) * lineSpacing
Dim flags As StringFormatFlags = StringFormatFlags.LineLimit Or
StringFormatFlags.FitBlackBox
Using format As StringFormat = New StringFormat(flags)
For x = 0 To sText.Length - 1
Dim textSize As SizeF = e.Graphics.MeasureString(sText(x), Font,
New SizeF(CSng(Width), CSng(Height)), format
)
e.Graphics.DrawString(sText(x), Font, Brushes.Black,
New RectangleF(0, relPositionY, textSize.Width, textSize.Height))
relPositionY += textSize.Height + paragraphSpacing
Next
End Using
End Sub
TextFormatFlags.WordBreak or TextFormatFlags.TextBoxControl
- Jimi