MiniDr
MiniDr

Reputation: 301

How to auto-size an Image based on the size of a string?

Is there a way to automatically fill a rectangle based on the width of string?
Currently, I am manually setting up the sizes and point of the rectangle based on the string.

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

Upvotes: 3

Views: 119

Answers (1)

Jimi
Jimi

Reputation: 32278

You could modify your ImgNotif() method to include the measure of the string.
Graphics.MeasureString() is the directly available tool, since you have already a Graphics context derived from the Image.

TextRederer.MeasureText() can also be used to perform this task.

StringFormat is used to setup some formatting options: alignment, text wrapping and clipping etc. (see the documentation).

Here, the text is centered on the Image.

Private Function ImgNotif(sourceImage As Image, imageText As String) As Image
    Dim bmp As New Bitmap(sourceImage)
    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(imageText, Me.Font, sourceImage.Size, format)
        Dim TextLocation As PointF = New PointF((sourceImage.Width - TextSize.Width) / 2 + 1, (sourceImage.Height - TextSize.Height) / 2 + 1)
        Dim rect As New RectangleF(TextLocation, TextSize)
        rect.Inflate(0, 1)
        g.FillRectangle(Brushes.OrangeRed, rect)
        g.DrawString(imageText, Me.Font, Brushes.White, rect, format)
    End Using
    Return bmp
End Function

Upvotes: 1

Related Questions