2010-05-20 137 views
3

我有这段代码;使用DrawString绘制无边框文字

public static Image AddText(this Image image, ImageText text) 
    { 
     Graphics surface = Graphics.FromImage(image); 
     Font font = new Font("Tahoma", 10); 

     System.Drawing.SolidBrush brush = new SolidBrush(Color.Red); 

     surface.DrawString(text.Text, font, brush, new PointF { X = 30, Y = 10 }); 

     surface.Dispose(); 
     return image; 
    } 

然而,当文本被绘制到我的形象,它是红色与黑色的边框或阴影。

如何在没有任何边框或阴影的情况下将文字写入图像?

EDIT

我通过添加解决了这个;

surface.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; 

如果有人能解释为什么我需要这样做会很好。

+0

如何将您的编辑移动到答案并选择最佳答案?这对我来说很有用。 – 2012-11-21 09:07:41

回答

3

你在那里看起来是正确的。见http://www.switchonthecode.com/tutorials/csharp-snippet-tutorial-how-to-draw-text-on-an-image

你可以尝试TextRenderer.DrawText(但请注意,它是System.Windows.Forms命名空间因此这可能可能是不合适的):

TextRenderer.DrawText(args.Graphics, text, drawFont, ClientRectangle, foreColor, backColor, TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter); 

为背景色尝试使用Color.Transparent。

还与图形,刷子,字体等工作时务必使用语句来包装他们,以便只保留他们身边,只要需要...

例如

using (var surface = Graphics.FromImage(image)) 
{ 
    var font = ... // Build font 
    using (var foreBrush = new SolidBrush(Color.Red)) 
    { 
     ... // Do stuff with brush 
    } 
} 
+1

+1使用关键字的提示。仍在寻找解决方案tho – griegs 2010-05-20 06:20:26

0

我认为那里不应该有任何边界。 它是边界还是阴影? 只需尝试使用另一种字体和字体大小+ FontStyle.Regular,看看是否有任何区别

+0

它看起来像一个影子。如果我把它缩小到30分,它看起来像一个影子。 – griegs 2010-05-20 06:03:38

3

当使用其默认透明背景在新创建的Bitmap对象上绘制彩色文本时,它周围有不完整的黑色边框。通过使用graphics.Clear(Color.White)初始化后解决了该问题。

+0

这真的起作用了,为什么黑色笔画会出现? – Pavel 2017-01-28 01:59:14