Search code examples
vb.netsystem.drawingsystem.drawing.graphics

VB.NET Drawing a two pixel transparent border around an on the fly created png image?


I'm quite new to programming graphics, much less with VB so I'm running to a wall here. I've done basically all the code all I'm missing is to add a few pixels of transparent padding/border around the image and I got stuck. I looked around but the examples I've seen seemed overwhelmingly complex and looked to me like an overkill (pages upon pages of code).

Any pointers or an easy to understand tutorials/examples would be extremely appreciated.

Appended the current code below:

Current code

Dim img As Image = New Bitmap(100, 100)

Dim Drawing As Graphics = Graphics.FromImage(img)
Dim rand As New Random
Dim bgcolor As Color = Color.FromArgb(rand.Next(64, 196), rand.Next(64, 196), rand.Next(64, 196))

Dim family As FontFamily = Nothing

Dim fontName As String = "Lucida Sans Typewriter"
Dim fontSize As Single = 42

Using fontTester As New Font(fontName, fontSize, FontStyle.Regular, GraphicsUnit.Pixel)
    If fontTester.Name = fontName Then 
        family = New FontFamily("Lucida Sans Typewriter")
    Else
        Try
            Dim privateFonts As New System.Drawing.Text.PrivateFontCollection()
            privateFonts.AddFontFile(HttpContext.Current.Server.MapPath("~/") + "\styles\fonts\LTYPE.ttf")
            Dim font As New System.Drawing.Font(privateFonts.Families(0), 42)
            family = font.FontFamily
        Catch ex As Exception
            family = New FontFamily("Arial")
        End Try
    End If
End Using

Dim FontText As Font = New Font(family, 42, FontStyle.Regular)

Drawing.Clear(bgcolor)
Dim textBrush As Brush = New SolidBrush(Color.White)
Drawing.DrawString(initials, FontText, textBrush, 7, 16)
Drawing.Save()
textBrush.Dispose()
Drawing.Dispose()

Solution

  • You can do so by clearing the image to transparent and then drawing a background rectangle that is 2 pixels smaller than the image in every direction:

    Drawing.Clear(Color.Transparent)
    Drawing.FillRectangle(New SolidBrush(bgcolor), 2, 2, 96, 96)
    'Draw text ...