1

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

我假设这是一个 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,我需要知道预测的文本有多大,以便我可以调整控件的大小并在控件中居中放置文本。

4

1 回答 1

3

试试MeasureString ()

gr.MeasureString("Header", New Font("MS SANS SERIF", 8.25, FontStyle.Regular, GraphicsUnit.Point, 1, True)).Width
于 2012-10-15T15:37:19.447 回答