Generate Image From Fonts

I have been asked to do this from time to time.
Because web browsers only support very few Chinese font style and designers thinks those fonts suck.

My method is a stupid one. Create a page and write out .png stream. Use this url as image url.

You can use an image file as its background or use a color as its background. I am using the generated image as an ImageButton’s image. The text is aligned to center.

How-To
1. Load the image file

 Bitmap bgImg = new Bitmap([ImagePath]);

2. Load font file

PrivateFontCollection privateFontCollection = new PrivateFontCollection();
privateFontCollection.AddFontFile([font path]);
FontFamily fontFamily = privateFontCollection.Families[0];
Font font = new Font(fontFamily, l_fontSize, FontStyle.Bold, GraphicsUnit.Pixel);

3. Create a brush

//input is either aarrggbb or color name

if (l_htmlColor.Contains("ff"))

{

l_htmlColor = string.Format("{0:s}{1:s}", "#", l_htmlColor.Substring(2));

l_foreColor = ColorTranslator.FromHtml(l_htmlColor);

}

else

{

l_foreColor = Color.FromName(l_htmlColor);

} SolidBrush myBrush = new SolidBrush([forecolor]);

4. write text to image

Graphics myGraph = Graphics.FromImage(myImage);
myGraph.DrawString(text, font, myBrush, new Rectangle(0, 0, l_btnWidth, l_btnHeight), new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });

Save the image to a memory stream and write it out.
That’s it. Please don’t use myXXX to name your variable as in my example. ^^

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s