字体的使用一般我们都是使用系统字体,这样比较方便,直接 Font font=new Font("微软雅黑",16f,FontStyle.Bold);
但是当我们用到一个系统没有的字体库时,这个方法就不好用了,因此我们可以采用动态加载字体文件的方式或者直接把字体打包到我们的程序集里当作资源来使用;
下面我们来看一下怎么用:
我封装了一个类,大家可以直接使用,如果有不好的地方,欢迎大家指正。
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 {
///
/// 字体库帮助类
///
public class FontHelper {
///
/// 通过字体文件获取字体
///
///
///
///
public static Font GetFontFromFile(string fontPath, float fontSize,FontStyle fontStyle) {
try {
//校验
if (!File.Exists(fontPath) || fontSize <= 0) {
return null;
}
//获取字体对象
PrivateFontCollection fontCollection = new PrivateFontCollection();
fontCollection.AddFontFile(fontPath);
var font = new Font(fontCollection.Families[0], fontSize, fontStyle);
return font;
}
catch (Exception ex) {
throw ex;
}
}
///
/// 通过资源流获取字体
///
///
///
///
public static Font GetFontFromStream(string fontName, float fontSize, FontStyle fontStyle) {
try {
//获取程序集
Assembly assembly = Assembly.GetExecutingAssembly();
//获取字体文件流
Stream stream = assembly.GetManifestResourceStream(fontName);
//读取字体到字节数组
byte[] fontData = new byte[stream.Length];
stream.Read(fontData, 0, (int)stream.Length);
stream.Close();
//获取字体对象
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;
}
}
}
}
使用方法如下:
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 {
///
/// 字体使用测试
///
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
protected override void OnLoad(EventArgs e) {
try {
//第1种用法
var font1 = FontHelper.GetFontFromStream("jackLib.fonthelper.Font.SourceCodePro-It.ttf", 20, FontStyle.Italic);
this.textBox1.Font = font1 ?? this.textBox1.Font;
//第2种用法
var font2 = FontHelper.GetFontFromFile(@"FontSourceCodePro-It.ttf", 20, FontStyle.Regular);
this.textBox1.Font = font2 ?? this.textBox1.Font;
}
catch (Exception ex) {
throw ex;
}
finally {
base.OnLoad(e);
}
}
}
}
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级