سؤال

I am using GDI+ to draw some white text outlined with black.

I tried using a graphics path but I got poor results (especially using small text sizes) so I thought about rendering black text at the 8 pixel positions around the text and then drawing white over the top.

The result is the sort of thing I want, but the code doesn't seem all that efficient. Is there a better way of achieving the same result?

My Code:

Private _whiteFont As New Font("Segoe UI", 8)
Private _blackFont As New Font("Segoe UI", 8)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    DrawTextWithOutline("12", New Point(18, 9))
End Sub

Private Sub DrawTextWithOutline(ByVal text As String, ByVal pt As Point)
    Using g As Graphics = Me.CreateGraphics
        g.DrawString(text, _blackFont, Brushes.Black, pt.X - 1, pt.Y) 'left
        g.DrawString(text, _blackFont, Brushes.Black, pt.X, pt.Y + 1) 'top
        g.DrawString(text, _blackFont, Brushes.Black, pt.X + 1, pt.Y) 'right
        g.DrawString(text, _blackFont, Brushes.Black, pt.X, pt.Y + 1) 'bottom
        g.DrawString(text, _blackFont, Brushes.Black, pt.X - 1, pt.Y - 1) 'top left
        g.DrawString(text, _blackFont, Brushes.Black, pt.X - 1, pt.Y + 1) 'bottom left
        g.DrawString(text, _blackFont, Brushes.Black, pt.X + 1, pt.Y - 1) 'top right
        g.DrawString(text, _blackFont, Brushes.Black, pt.X + 1, pt.Y + 1) 'bottom right
        g.DrawString(text, _whiteFont, Brushes.White, pt)
    End Using
End Sub

Sample Result: enter image description here

هل كانت مفيدة؟

المحلول

You didn't post your GraphicsPath attempt, but this version seems to draw ok. I used a bold font to try to get more white space inside and a 2-pixel black pen to get the outline:

e.Graphics.SmoothingMode = SmoothingMode.AntiAlias
Using gp As New GraphicsPath, _
      f As New Font("Segoe UI", 8, FontStyle.Bold), _
      p As New Pen(Brushes.Black, 2)
  gp.AddString(text, f.FontFamily, f.Style, f.Size + 3, New Point(100, 40), _
               StringFormat.GenericTypographic)
  e.Graphics.DrawPath(p, gp)
  e.Graphics.FillPath(Brushes.White, gp)
End Using

Beauty is in the eye of the beholder:

enter image description here

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top