Skip to content

Instantly share code, notes, and snippets.

@nathanchere
Last active January 4, 2016 03:08
Show Gist options
  • Save nathanchere/8559374 to your computer and use it in GitHub Desktop.
Save nathanchere/8559374 to your computer and use it in GitHub Desktop.
Resource font loader
/*
Makes it easier to distribute and use fonts by embedding them in your application as a resource.
Example:
var fontLoader = new ResourceFont(Properties.Resources.font_ComicSerif);
textBox1.Font = fontLoader.GetFont(16);
*/
public class ResourceFont
{
private PrivateFontCollection _font;
public ResourceFont(byte[] rawFont)
{
System.IntPtr data = new IntPtr();
try
{
_font = new PrivateFontCollection();
using (var stream = new MemoryStream(rawFont)) {
data = Marshal.AllocCoTaskMem((int)stream.Length);
Marshal.Copy(rawFont, 0, data, (int)stream.Length);
_font.AddMemoryFont(data, (int)stream.Length);
}
}
finally
{
Marshal.FreeCoTaskMem(data);
}
}
public Font GetFont(float ems)
{
if (_font == null || _font.Families.Length == 0) throw new InvalidDataException("No font data loaded");
return new Font(_font.Families[0], ems);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment