【问题标题】:Text in drawn image is in wrong font (C#)绘制图像中的文本字体错误(C#)
【发布时间】:2015-04-25 02:25:31
【问题描述】:

我正在尝试编写一个代码,为给定的文本块输出 PNG 图像。我正在使用System.Drawing 来实现这一点。

我的问题是输出图像中的文字字体错误。

这是我用来绘制输出的函数代码:

static Bitmap FromTextToPic(string text, Int16 size)
    {
        //create dummy Bitmap object
        Bitmap bitmapImage = new Bitmap(2, 2);

        //create dummy measurements
        int imageWidth = 0;
        int imageHeight = 0;

        //naming font
        font = "Lohit-Devanagari";

        // Creates the Font object for the image text drawing.
        System.Drawing.Font fontObject = new System.Drawing.Font(font, size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);

        // Creates a graphics object to measure the text's width and height.
        Graphics graphicsObject = Graphics.FromImage(bitmapImage);

        // This is where the bitmap size is determined.
        imageWidth = (int)graphicsObject.MeasureString(text, fontObject).Width;
        imageHeight = (int)graphicsObject.MeasureString(text, fontObject).Height;

        // Creates the bmpImage again with the correct size for the text and font.
        bitmapImage = new Bitmap(bitmapImage, new Size(imageWidth, imageHeight));


        // Adds the colors to the new bitmap.
        graphicsObject = Graphics.FromImage(bitmapImage);

        // Sets Background color to white
        graphicsObject.Clear(System.Drawing.Color.White);

        //enables optimization for LCD screens
        graphicsObject.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //enables antialiasing
        graphicsObject.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; 

        //draws text to picture with black foreground color
        graphicsObject.DrawString(text, fontObject, new SolidBrush(System.Drawing.Color.Black), 0, 0, StringFormat.GenericDefault);

        graphicsObject.Flush();

        return (bitmapImage);
    }

即使我将“Lohit-Devanagari”指定为字体,我总是以“Mangal”字体(两者都是 Devanagari 字体)获得输出。那么,我做错了什么?

此外,如果文本中没有换行符(如this picture),则输出会延伸很长一段距离。有没有办法将输出图像包装成某个固定宽度?

【问题讨论】:

    标签: c# drawing system.drawing


    【解决方案1】:

    而不是这个:

    //naming font
    font = "Lohit-Devanagari";
    

    试试这个:

    //naming font
    FontFamily font = new FontFamily("Lohit Devanagari");
    

    字体名称可能没有“-”字符。

    如果你声明了一个新的对象FontFamily,如果字体不存在就会抛出异常。所以你必须下载安装它...

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 2018-05-30
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 2017-07-07
      相关资源
      最近更新 更多