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

ozk*_*zke 2 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);
Run Code Online (Sandbox Code Playgroud)

但它使用默认字体创建文本块.有任何想法吗?

提前致谢 :)

Chr*_*ett 5

如果您可以将其加载到Stream中,请尝试使用PrivateFontCollection.我对另一个问题的回答中的示例代码.

编辑:请参阅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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)