2010-05-20 38 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