自动调整大小Rectangle取决于String

时间:2018-05-23 03:18:38

标签: vb.net

有没有办法根据字符串的宽度自动填充矩形?
目前,我是根据字符串手动设置矩形的大小和点。

Public Class test
    Public Sub New()
        InitializeComponent()
        NavButton3.Glyph = ImgNotif(NavButton3.Glyph, "99") ' My image size is 32 x 32
    End Sub

    Private Function ImgNotif(srcImg As Image, num As String) As Image
        Dim bmp As New Bitmap(srcImg)
        Dim rect As New Rectangle(16, 16, 16, 16)
        Using g As Graphics = Graphics.FromImage(bmp)
            g.FillRectangle(Brushes.OrangeRed, rect)
            g.DrawString(num, Me.Font, Brushes.White, New Point(16, 16))
        End Using
        Return bmp
    End Function
End Class


enter image description here

1 个答案:

答案 0 :(得分:1)

您可以修改ImgNotif()方法以包含字符串的度量 Graphics.MeasureString()是直接可用的工具,因为您已经从图像派生出了图形上下文。

TextRederer.MeasureText()也可用于执行此任务。

StringFormat用于设置一些格式选项,对齐,文本换行和剪辑等。(请参阅文档)。
在这里,文本以图像为中心。

Private Function ImgNotif(srcImg As Image, num As String) As Image

    Using bmp As New Bitmap(srcImg)
        Using g As Graphics = Graphics.FromImage(bmp)
            Dim format As StringFormat = New StringFormat(StringFormatFlags.NoWrap)
            format.Alignment = StringAlignment.Center
            format.LineAlignment = StringAlignment.Center
            Dim TextSize As SizeF = g.MeasureString(num, Me.Font, srcImg.Size, format)
            Dim TextLocation As PointF = New PointF((srcImg.Width - TextSize.Width) / 2 + 1, (srcImg.Height - TextSize.Height) / 2 + 1)
            Dim rect As New RectangleF(TextLocation, TextSize)
            rect.Inflate(0, 1)
            g.FillRectangle(Brushes.OrangeRed, rect)
            g.DrawString(num, Me.Font, Brushes.White, rect, format)
        End Using
        Return CType(bmp.Clone(), Image)
    End Using

End Function