如何为Font生成正确的位图?

时间:2011-04-07 08:31:26

标签: c# .net graphics fonts bitmap

我有一个关于位图字体的问题。我需要为屏幕设备创建字体。它应该包含所有可打印字符的位图。要获得所有字符的位图,我使用以下方法:

public MFont(Font font, int first = 32, int last = 126)
{        
    var characters = new List<Character>();
    Bitmap objBmpImage = new Bitmap(1, 1);

    // Create a graphics object to measure the text's width and height.
    Graphics objGraphics = Graphics.FromImage(objBmpImage);

    for (int i = first; i <= last; i++)
    {
        char c = Convert.ToChar(i);
        int intWidth;
        int intHeight;
        string s = "" + c;

        // This is where the bitmap size is determined.                
        intWidth = (int)objGraphics.MeasureString(s, font).Width;
        intHeight = (int)objGraphics.MeasureString(s, font).Height;

        // Create the bmpImage again with the correct size for the text and font.
        objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));    

        objGraphics = Graphics.FromImage(objBmpImage);    
        // Set Background color
        objGraphics.Clear(Color.White);
        objGraphics.SmoothingMode = SmoothingMode.None;
        objGraphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
        objGraphics.DrawString(s, font, new SolidBrush(Color.Black), 0, 0);           
        objGraphics.Flush();                  

        characters.Add(
            new Character
                {
                    Bitmap = objBmpImage,
                    Code = i,
                    Size = objBmpImage.Size                        

                }
            );
    }
}

问题是所有字符位图在左侧和右侧都有太多空间。因此,当我在屏幕上使用位图显示文本时,文本就像在每个字符后添加一个空格。我该怎么修呢?也许有些东西我不了解字体,或者它们应该如何显示。我知道我可以手动裁剪位图,但这不是很准确和清晰。除此之外,一些角色根本没有任何冗余空间。

2 个答案:

答案 0 :(得分:2)

尝试使用TextRenderer.MeasureText()代替Graphics.MeasureString()。它允许您指定测量期间将使用的TextFormatFlags。我怀疑默认情况下会添加填充,因此请尝试将TextFormatFlags.NoPadding传递给方法,看看您的结果是否发生了变化。

答案 1 :(得分:2)

两边的额外空间都是填充物。您必须在标志上指定NoPadding。阅读以下链接:

http://msdn.microsoft.com/en-us/magazine/cc751527.aspx

另外,请注意字符串测量可能会考虑斜体文本所需的空间 - 因此您可能在每个字符的右侧有额外的间距。

你说有些字符没有多余的空格。这意味着您看到的额外间距可能是由于字距调整或缺少字距。

你必须实现你自己的“字距调整”来压缩字符(对于比例字体)。否则,你总是看起来不太理想。

有很多方法可以捏造字距调整,但它需要你对位图进行一些后期处理。

相关问题