使用自定义字体问题
本文关键字:体问题 字体 自定义 | 更新日期: 2023-09-27 18:28:38
我有一个自定义字体文件,我想在我的应用程序上使用,目前我使用的是.net framework2,这是我使用的代码:
private void Form1_Load(object sender, EventArgs e)
{
//load the resource
Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("Eurostile_Regular_0.ttf");
//create an unsafe memory block for the data
System.IntPtr data = Marshal.AllocCoTaskMem(Convert.ToInt16(fontStream.Length));
//create a buffer to read in to
byte[] fontdata = null;
fontdata = new byte[fontStream.Length + 1];
//fetch the font program from the resource
fontStream.Read(fontdata, 0, Convert.ToInt16(fontStream.Length));
//copy the bytes to the unsafe memory block
Marshal.Copy(fontdata, 0, data, Convert.ToInt16(fontStream.Length));
//pass the font to the font collection
pfc.AddMemoryFont(data, Convert.ToInt16(fontStream.Length));
//close the resource stream
fontStream.Close();
//free the unsafe memory
Marshal.FreeCoTaskMem(data);
}
在Form1_Paint上:
private void Form1_Paint(object sender, PaintEventArgs e)
{
bool bold = false;
bool regular = false;
bool italic = false;
e.Graphics.PageUnit = GraphicsUnit.Point;
SolidBrush b = new SolidBrush(Color.Black);
float y = 5;
System.Drawing.Font fn;
foreach (FontFamily ff in pfc.Families)
{
if (ff.IsStyleAvailable(FontStyle.Regular))
{
regular = true;
fn = new Font(ff, 18, FontStyle.Regular);
e.Graphics.DrawString(fn.Name, fn, b, 5, y, StringFormat.GenericTypographic);
fn.Dispose();
y += 20;
}
if (ff.IsStyleAvailable(FontStyle.Bold))
{
bold = true;
fn = new Font(ff, 18, FontStyle.Bold);
e.Graphics.DrawString(fn.Name, fn, b, 5, y, StringFormat.GenericTypographic);
fn.Dispose();
y += 20;
}
if (ff.IsStyleAvailable(FontStyle.Italic))
{
italic = true;
fn = new Font(ff, 18, FontStyle.Italic);
e.Graphics.DrawString(fn.Name, fn, b, 5, y, StringFormat.GenericTypographic);
fn.Dispose();
y += 20;
}
if (bold && italic)
{
fn = new Font(ff, 18, FontStyle.Bold | FontStyle.Italic);
e.Graphics.DrawString(fn.Name, fn, b, 5, y, StringFormat.GenericTypographic);
fn.Dispose();
y += 20;
}
fn = new Font(ff, 18, FontStyle.Underline);
e.Graphics.DrawString(fn.Name, fn, b, 5, y, StringFormat.GenericTypographic);
fn.Dispose();
y += 20;
fn = new Font(ff, 18, FontStyle.Strikeout);
e.Graphics.DrawString(fn.Name, fn, b, 5, y, StringFormat.GenericTypographic);
fn.Dispose();
}
b.Dispose();
}
但是字体不起作用,我从form_load 的第二行得到JIT错误
System.NullReferenceException:对象引用未设置为对象的实例。
首先转到您的Font Properties
->Build Action
->"Embedded Resource"
其次,你的问题是你忘记在代码中添加你的NameSpace名称
错误的格式
Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("FileName.ttf");
正确的格式
Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("NameSpaceName.FileName.ttf");
祝好运
fontStream为null,因为GetManifestResourceStream找不到您的字体。您的字体必须添加到解决方案中,然后选择";嵌入式资源";在生成操作下的属性中。看起来您可能试图嵌入字体,但没有在流请求中正确命名。添加您的项目资源集合:
Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("yourApp.Eurostile_Regular_0.ttf");
您可以在这里获得更多信息:如何嵌入True Type Font