最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C# jackLib系列之字体使用详解
时间:2016-08-13 编辑:简简单单 来源:一聚教程网
字体的使用一般我们都是使用系统字体,这样比较方便,直接 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(@"Font\SourceCodePro-It.ttf", 20, FontStyle.Regular);
this.textBox1.Font = font2 ?? this.textBox1.Font;
}
catch (Exception ex) {
throw ex;
}
finally {
base.OnLoad(e);
}
}
}
}
相关文章
- C#复制数组的两种方式及效率比较解读 10-24
- C语言中atoi函数模拟实现介绍 10-18
- C#中ArrayList 类的使用介绍 09-22
- C#非托管泄漏中HEAP_ENTRY的Size对不上解析问题解决方法 09-22
- C#序列化与反序列化集合对象并进行版本控制的方法 09-19
- C#枚举高级战术代码解析 10-13