VB.NET: Finding the size of text to be drawn, befo

2019-07-28 09:59发布

问题:

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.

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

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.

回答1:

Try MeasureString()

gr.MeasureString("Header", New Font("MS SANS SERIF", 8.25, FontStyle.Regular, GraphicsUnit.Point, 1, True)).Width