Im a little bit confused because I can display every string with every font on my windows form but as an image it is not always possible. Maybe there is just something wrong with my code. But let me show you what I was trying.
At first I have this:
Label l = new Label();
l.Text = "Ì CSharp Î";
this.Font = new Font("Code 128", 80);
l.Size = new System.Drawing.Size(300, 200);
this.Controls.Add(l);
this.Size = new Size(300, 200);
Well this is very fine. Now I would like to try to save the same string with the same font as image. I found this code and I thought thats how to do this
private static Image DrawText(string text, Font font, Color textColor, Color backColor)
{
//first, create a dummy bitmap just to get a graphics object
Image img = new Bitmap(1, 1);
Graphics drawing = Graphics.FromImage(img);
//measure the string to see how big the image needs to be
SizeF textSize = drawing.MeasureString(text, font);
//free up the dummy image and old graphics object
img.Dispose();
drawing.Dispose();
//create a new image of the right size
img = new Bitmap((int)textSize.Width, (int)textSize.Height);
drawing = Graphics.FromImage(img);
//paint the background
drawing.Clear(backColor);
//create a brush for the text
Brush textBrush = new SolidBrush(textColor);
drawing.DrawString(text, font, textBrush, 0, 0);
drawing.Save();
textBrush.Dispose();
drawing.Dispose();
return img;
}
var i = DrawText("Ì CSharp Î", new Font("Code 128", 40), Color.Black, Color.White);
If I save the image I get this:
I dont get it. Im using the same string and the same font as I used it on my windows form. Why is that so? And how to avoid this problem?
PS: The font that Im using was downloaded here but I tested it with other fonts too and its not always working.