加载外部字体并在C#中使用它

时间:2009-05-24 23:22:50

标签: c# wpf fonts load

我想从外部服务器加载一个字体,一旦加载(我想这是必要的)用它来创建一些文本字段。

我正在尝试:

font_uri = new Uri("http://localhost/assets/fonts/wingding.ttf");
bf_helvetica = new FontFamily(font_uri, "bf_helvetica");

TextBlock test_tb = new TextBlock();
test_tb.Text = "This is a test";
test_tb.FontSize = 16;
test_tb.Foreground = Brushes.Red;
test_tb.FontFamily = bf_helvetica;
stage.Children.Add(test_tb);

但是它会使用默认字体创建文本块。 有什么想法吗?

提前致谢:)

3 个答案:

答案 0 :(得分:5)

如果您可以将其加载到Stream中,请尝试使用PrivateFontCollectionmy answer to another question中的示例代码。

编辑:请参阅System.Net.WebRequest.GetRequestStream,将URI加载到Stream中,然后将该流加载到PFC中,如链接代码中所述。

另外,我会在本地保存文件,并先在那里查找,所以每次运行程序时都不必下载它。

再次编辑:抱歉,不是WebRequest.GetRequestStream,您需要WebResponse.GetResponseStream()。以下是一些示例代码,可以完全满足您的需求。

using System;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace RemoteFontTest
{
    public partial class Form1 : Form
    {
        readonly PrivateFontCollection pfc = new PrivateFontCollection();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WebRequest request = WebRequest.Create(@"http://somedomain.com/foo/blah/somefont.ttf");
            request.Credentials = CredentialCache.DefaultCredentials;

            WebResponse response = request.GetResponse();

            using (Stream fontStream = response.GetResponseStream())
            {
                if (null == fontStream)
                {
                    return;
                }

                int fontStreamLength = (int)fontStream.Length;

                IntPtr data = Marshal.AllocCoTaskMem(fontStreamLength);

                byte[] fontData = new byte[fontStreamLength];
                fontStream.Read(fontData, 0, fontStreamLength);

                Marshal.Copy(fontData, 0, data, fontStreamLength);

                pfc.AddMemoryFont(data, fontStreamLength);

                Marshal.FreeCoTaskMem(data);
            }
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            using (SolidBrush brush = new SolidBrush(Color.Black))
            {
                using (Font font = new Font(pfc.Families[0], 32, FontStyle.Regular, GraphicsUnit.Point))
                {
                    e.Graphics.DrawString(font.Name, font, brush, 10, 10, StringFormat.GenericTypographic);
                }
            }
        }
    }
}

答案 1 :(得分:0)

传递给FontFamily构造函数的姓氏实际上是字体文件公开的姓氏吗?在您的示例中,如果您加载了Wingding.ttf,则字体系列名称将为Wingdings,而不是bf_helvetica。如果字体文件是bf_helvetica.ttf,则姓氏可能不是字体名称,如Helvetica或Helvetica Bold。

答案 2 :(得分:0)

我发布了真正类型字体的解决方案,但它可以与其他类型一起使用。

C# HOW TO ADD A TTF TO the project in Visual Studio

http://hongouru.blogspot.com/2010/10/c-how-to-add-fonts-ttf-true-type-fonts.html

我希望它有所帮助。

相关问题