我有,我想在我的應用程序中使用自定義的字體文件,目前我使用.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:對象引用未設置爲一個對象的實例。
該錯誤可能是因爲fontStream是空的意思你是不是成功地從你的資源加載它。您正在使用的名稱在某些方面可能不正確。 – 2012-03-20 20:17:37