sprayingmantis
sprayingmantis

Reputation: 13

Text in drawn image is in wrong font (C#)

I'm trying to write a code that outputs a PNG image for a given block of text. I'm using System.Drawing to achieve this.

My problem is that the text in output image is in wrong font.

Here is the code of the function that I'm using in order to draw the output:

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);
    }

Even when I'm specifying "Lohit-Devanagari" as the font, I always get the output in "Mangal" font (both are Devanagari fonts). So, what have I done wrong?

Also, the output stretches over to a long distance if there isn't a newline character in text (as in this picture). Is there a way to wrap up the output image to some fixed width?

Upvotes: 1

Views: 320

Answers (1)

SChniter
SChniter

Reputation: 36

Instead of this:

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

Try this:

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

The font name are probably without the "-" character.

If you declare a new object FontFamily, it will make an exception if the font does not exist.So you have to download and install it ...

Upvotes: 1

Related Questions