VB.NET:在绘制到控件之前查找要绘制的文本的大小

时间:2012-10-15 15:24:38

标签: vb.net winforms text system.drawing

我正在创建用户控件并向其添加文本大小属性。我需要知道文本大小在将其绘制到控件上之前的大小,以便我可以将其置于控件的高度和宽度上。

我假设这是一个Windows API命令。但是我无法找到任何相关信息。

 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,我需要知道预测文本的大小,以便我可以调整控件的大小并使控件中的文本居中。

1 个答案:

答案 0 :(得分:3)

尝试MeasureString()

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