我想从外部服务器加载字体,加载后(我想这是必要的)使用它来创建一些文本字段。
我正在尝试:
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);
但它使用默认字体创建文本 block 。 有什么想法吗?
提前致谢:)
最佳答案
如果您可以将其加载到流中,请尝试使用 PrivateFontCollection 。 my answer to another question 中的示例代码.
编辑:参见System.Net.WebRequest.GetRequestStream ,将 URI 加载到 Stream 中,然后将该 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);
}
}
}
}
}
关于c# - 加载外部字体并在 C# 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/904857/