VB.NET:在绘制到控件之前查找要绘制的文本的大小 [英] VB.NET: Finding the size of text to be drawn, before it is drawn to a control
问题描述
我正在创建一个用户控件并向其添加文本大小属性.在控件上绘制文本之前,我需要知道文本大小有多大,以便我可以将其相对于其高度和宽度在控件上居中.
I'm creating a user control and adding a text size property to it. I need to know how big the text size is going to be before drawing it on the control so that I can center it on the control in relation to its height and width.
我假设这是一个 Windows API 命令.但是,我一直无法找到有关它的任何信息.
I'm under the assumption that this is a windows API command. However I have not been able to locate any information on it.
Public Sub DrawImage(ByVal gr As Graphics)
If Me.Image Is Nothing Then Return
Dim r As Rectangle = New Rectangle(8, 8, Me.ImageSize.Width, Me.ImageSize.Height)
Select Case Me.ImageAlign
Case ContentAlignment.TopLeft
r = New Rectangle(4, 4, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.TopCenter
r = New Rectangle((Me.Width / 2 - Me.ImageSize.Width / 2) / 2, 4, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.TopRight
r = New Rectangle(Me.Width - 4 - Me.ImageSize.Width, 4, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.MiddleLeft
r = New Rectangle(8, Me.Height / 2 - Me.ImageSize.Height / 2, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.MiddleCenter
r = New Rectangle(Me.Width / 2 - Me.ImageSize.Width / 2, Me.Height / 2 - Me.ImageSize.Height / 2, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.MiddleRight
r = New Rectangle(Me.Width - 8 - Me.ImageSize.Width, Me.Height / 2 - Me.ImageSize.Height / 2, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.BottomLeft
r = New Rectangle(8, Me.Height - 8 - Me.ImageSize.Height, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.BottomCenter
r = New Rectangle(Me.Width / 2 - Me.ImageSize.Width / 2, Me.Height - 8 - Me.ImageSize.Height, Me.ImageSize.Width, Me.ImageSize.Height)
Case ContentAlignment.BottomRight
r = New Rectangle(Me.Width - 8 - Me.ImageSize.Width, Me.Height - 8 - Me.ImageSize.Height, Me.ImageSize.Width, Me.ImageSize.Height)
End Select
gr.DrawString("Header", New Font("MS SANS SERIF", 8.25, FontStyle.Regular, GraphicsUnit.Point, 1, True), Brushes.Black, 0, 0)
'gr.DrawImage(Me.Image, r)
End Sub
如您所见@gr.DrawString,我需要知道文本的预测大小,以便我可以调整控件的大小并将文本居中.
As you can see @ gr.DrawString, I need to know how big the text is predicted to be so that I can size the control and center the text within the control.
推荐答案
尝试 MeasureString()
gr.MeasureString("Header", New Font("MS SANS SERIF", 8.25, FontStyle.Regular, GraphicsUnit.Point, 1, True)).Width
这篇关于VB.NET:在绘制到控件之前查找要绘制的文本的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!