Font use generally we are using system fonts, so more convenient, direct font font=new font ("Microsoft Ya Black", 16f,fontstyle.bold);
But when we use a font library that is not available to the system, this method is not used, so we can use the font file dynamically or simply package the font into our assembly as a resource;
Now let's take a look at how to use:
I encapsulate a class that you can use directly, if there is a bad place, you are welcome to correct me.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Drawing.Text;
Using System.Drawing;
Using System.IO;
Using System.Reflection;
Namespace Jacklib.fonthelper {
<summary>
Font Library Help Class
</summary>
public class Fonthelper {
<summary>
Get fonts from Font files
</summary>
<param name= "Fontpath" ></param>
<param name= "FontSize" ></param>
<returns></returns>
public static Font Getfontfromfile (string fontpath, float Fontsize,fontstyle fontstyle) {
try {
Check
if (! File.exists (Fontpath) | | FontSize <= 0) {
return null;
}
Get Font Object
PrivateFontCollection fontcollection = new PrivateFontCollection ();
Fontcollection.addfontfile (Fontpath);
var font = new Font (fontcollection.families[0], fontsize, FontStyle);
return font;
}
catch (Exception ex) {
Throw ex;
}
}
<summary>
Get fonts from resource flow
</summary>
<param name= "FontName" ></param>
<param name= "FontSize" ></param>
<returns></returns>
public static Font Getfontfromstream (string fontname, float fontsize, FontStyle fontstyle) {
try {
Get assembly
Assembly Assembly = assembly.getexecutingassembly ();
Get font file stream
Stream stream = assembly. GetManifestResourceStream (FontName);
Reading font to byte array
byte[] Fontdata = new Byte[stream. Length];
Stream. Read (fontdata, 0, (int) stream. Length);
Stream. Close ();
Get Font Object
PrivateFontCollection PFC = new PrivateFontCollection ();
unsafe {
Fixed (byte* pfontdata = fontdata) {
Pfc. Addmemoryfont ((System.IntPtr) pfontdata, fontdata.length);
}
}
return new Font (Pfc. Families[0], FontSize, FontStyle);
}
catch (Exception ex) {
Throw ex;
}
}
}
}
Use the following methods:
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Namespace Jacklib.fonthelper {
///<summary>
///font usage Test
///</summary>
public partial class Form1:form {
public Form1 () {
InitializeComponent ();
}
protected override void OnLoad (EventArgs e) {
try {
//1th usage
var font1 = Fonthelper.getfontfromstream (" Jacklib.fonthelper.font.sourcecodepro-it.ttf ", fontstyle.italic);
This.textBox1.Font = Font1?? This.textBox1.Font;
//2nd usage
var font2 = Fonthelper.getfontfromfile (@ "Font\sourcecodepro-it.ttf", fontstyle.regular);
This.textBox1.Font = Font2?? This.textBox1.Font;
}
catch (Exception ex) {
throw ex;
}
finally {
base. OnLoad (e);
}
}
}
}