强制包装字符串时如何在Y轴上居中显示文本

时间:2013-12-02 19:10:50

标签: vb.net gdi+

我强制包装一些文字。当我这样做时,循环中使用以下方法;它返回下一行的Y线(基于字符串高度)。这就像一个魅力,但我失去了垂直居中文本的能力。

我正在寻找有关如何增强此方法以允许垂直居中的建议。

 <Extension()> _
        Public Function DrawText(ByVal p_graphics As Graphics, ByVal p_text As String, ByVal p_Font As Font, ByVal p_fontColor As Brush, ByVal p_X As Decimal, ByVal p_Y As Decimal, _
                                 ByVal p_boundingWidth As Decimal, ByVal p_StringFormat As StringFormat) As Decimal

            If String.IsNullOrEmpty(p_text) Then
                Return p_Y
            End If

            Dim _sizef As SizeF = p_graphics.MeasureString(p_text, p_Font, Integer.MaxValue, p_StringFormat)
            Dim _LineCnt As Integer = Math.Ceiling(_sizef.Width / p_boundingWidth)
            Dim _height As Integer = Math.Ceiling(_LineCnt * Math.Ceiling(_sizef.Height))

            p_graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
            Dim _rec As New RectangleF(p_X, p_Y, p_boundingWidth, _height)
            p_graphics.DrawString(p_text, p_Font, p_fontColor, _rec, p_StringFormat)
            Return (p_Y + _rec.Height)
        End Function

我如何使用此扩展方法的示例(编写此空闲手,因此语法可能不正确):

.
.
.
    Using g as graphics.FromImage(_MyImage)
        Dim _LineStart as integer = 0
        Foreach _line as string in _Lines 'List of String
         _LineStart = g.DrawText(line, _font, Obj.FontColorBrush, 0, _LineStart, Obj.DPIWidth, Obj.StringFormat)
        End For
    End Using
.
.
.

1 个答案:

答案 0 :(得分:0)

好的,现在我想我明白了。您需要计算从哪里开始垂直绘制。

我在表单上放了一个PictureBox和一个Button,添加了你的扩展方法,并使用了这段代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim lines As New List(Of String)
    lines.Add("The quick brown")
    lines.Add("fox jumps over")
    lines.Add("the lazy dog.")
    lines.Add("This line is too wide to fit the available space.")

    Dim fmt = StringFormat.GenericTypographic
    fmt.Alignment = StringAlignment.Center

    Using fnt = New Font("Arial", 8)
        Using brsh = New SolidBrush(Color.Black)
            Using g = PictureBox1.CreateGraphics

                Dim lineY As Integer = (PictureBox1.Height - lines.Count * fnt.Height) \ 2

                For Each line As String In lines
                    lineY = CInt(g.DrawText(line, fnt, brsh, 0, lineY, PictureBox1.Width, fmt))
                Next

            End Using
        End Using
    End Using

End Sub

Example result

当我使用Option Strict On时,我不得不对您的DrawText方法进行一些小修改。

注意过长的行是如何被截断的。居中,但截断。这就是可能想要使用Graphics.MeasureString方法(String,Font,SizeF,StringFormat)重载的地方,以便您可以自动包装。这当然会弄乱垂直居中的计算。