I have added a custom font using below code:
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("C:\\Path To\\YourFont.ttf");
label1.Font = new System.Drawing.Font(pfc.Families[0], 16, FontStyle.Regular);
I added the font file in resources. How do I add with addFontFile
from resources?
private static void AddFontFromResource(PrivateFontCollection privateFontCollection, string fontResourceName)
{
var fontBytes = GetFontResourceBytes(typeof (App).Assembly, fontResourceName);
var fontData = Marshal.AllocCoTaskMem(fontBytes.Length);
Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length);
privateFontCollection.AddMemoryFont(fontData, fontBytes.Length);
// Marshal.FreeCoTaskMem(fontData); Nasty bug alert, read the comment
}
private static byte[] GetFontResourceBytes(Assembly assembly, string fontResourceName)
{
var resourceStream = assembly.GetManifestResourceStream(fontResourceName);
if (resourceStream == null)
throw new Exception(string.Format("Unable to find font '{0}' in embedded resources.", fontResourceName));
var fontBytes = new byte[resourceStream.Length];
resourceStream.Read(fontBytes, 0, (int)resourceStream.Length);
resourceStream.Close();
return fontBytes;
}
This is the way I do it.
First get your Font.ttf file and using Visual Studio, drag and drop the file to the root folder or resource folder.
In Solution Explorer, right-click the file and click properties. Select Build Action = Content
. This will show the file in the Application Files under Project Properties > Publish > Application Files. You will see that the file now can be selected (By default it's automatically included).
ClickOnce will now copy the file to the StartupPath
To use it, follow this sample:
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(Path.Combine(Application.StartupPath, "font_name.ttf"));
textBox1.Font = new Font(pfc.Families[0], 18, FontStyle.Regular);
If you included your font in the resources
Try this function
private void AddFontFromMemory()
{
Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("yourfont.ttf");
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata,0,(int)fontStream.Length);
fontStream.Close();
unsafe
{
fixed(byte * pFontData = fontdata)
{
pfc.AddMemoryFont((System.IntPtr)pFontData,fontdata.Length);
}
}
}
Edited
How load resource from assembly:(YourNamespace.file.ttf)
Stream fontStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("WindowsFormsApplication1.SBADR.TTF");
My solution explorer:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With