Last active
January 4, 2016 03:08
-
-
Save nathanchere/8559374 to your computer and use it in GitHub Desktop.
Resource font loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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