2010-04-21 43 views
0

我試圖創建一個圖像上有一些文字,我希望圖像的大小與渲染文本的大小相匹配。如何獲得不帶填充的繪製字符串的尺寸?

當我使用System.Windows.Forms.TextRenderer.MeasureText(...)要測量的文本,我得到維度包括字體填充。當文本呈現時,它似乎使用相同的填充。

有什麼方法來確定文本字符串的大小,然後使其沒有任何填充?

這是我試過的代碼:

// Measure the text dimensions 
var text = "Hello World"; 
var fontFamily = new Font("Arial", 30, FontStyle.Regular); 
var textColor = new SolidBrush(Color.Black); 
Size textSize = TextRenderer.MeasureText(text, fontFamily, 
          Size.Empty, TextFormatFlags.NoPadding); 

// Render the text with the given dimensions 
Bitmap bmp = new Bitmap(textSize.Width, textSize.Height); 
Graphics g = Graphics.FromImage(bmp); 
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; 
g.DrawString(text, fontFamily, textColor, new PointF(0, 0));    
bmp.Save("output.png", ImageFormat.Png); 

這是目前被呈現出來:

Current Output

這就是我想要呈現的內容:

Desired Output

我也看了成Graphics.MeasureString(...),但只能在現有Graphics對象上使用。我想在創建圖像之前知道尺寸。此外,調用Graphics.MeasureString(...)返回相同的尺寸,所以它不會幫助我。

回答

1

我認爲這是因爲字體高度爲46 30point字體。
這樣您就可以擁有特殊的大寫字母(愛沙)和情侶字符(gqp)。
前導和尾隨空格可能也與此有關。

+0

就是這樣! http://i.imgur.com/Py4zK.png – 2010-04-21 11:17:49