我可以改进此代码以绘制轮廓文本

时间:2013-10-17 14:24:10

标签: .net vb.net gdi+ text-rendering

我正在使用GDI +绘制一些用黑色勾勒出来的白色文字。

我尝试使用图形路径,但结果不佳(特别是使用小文本大小),所以我考虑在文本周围的8个像素位置渲染黑色文本,然后在顶部绘制白色。

结果是我想要的东西,但代码看起来并不那么有效。有没有更好的方法来实现相同的结果?

我的代码:

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

示例结果: enter image description here

1 个答案:

答案 0 :(得分:4)

你没有发布你的GraphicsPath尝试,但这个版本似乎画得好。我使用粗体字来尝试在内部获得更多的空白区域,使用2像素的黑色笔来获得轮廓:

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

美丽在旁观者眼中:

enter image description here