字体的使用一般我们都是使用系统字体,这样比较方便,直接 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);
}
}
}
}
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔