VB.NET: Finding the size of text to be drawn, before it is drawn to a control

六月ゝ 毕业季﹏ 提交于 2019-12-11 07:58:02

问题


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


来源:https://stackoverflow.com/questions/12898841/vb-net-finding-the-size-of-text-to-be-drawn-before-it-is-drawn-to-a-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!