25

我的 Winform 上有一个标签,我想使用一种名为 XCalibur 的自定义字体,让它看起来更时髦。

如果我在标签上使用自定义字体,然后构建解决方案,然后将文件压缩到 \bin\Release 中,最终用户是否会看到带有我使用的自定义应用程序的标签,无论他们是否安装了该字体?

如果不是这种情况,在 Labels.Text 上使用自定义字体的正确方法是什么?

4

4 回答 4

53

在浏览了可能的 30-50 个帖子之后,我终于能够想出一个真正有效的解决方案!请按顺序执行以下步骤:

1.) 在您的应用程序资源中包含您的字体文件(在我的例子中是 ttf 文件)。为此,请双击“ Resources.resx ”文件。

在此处输入图像描述

2.) 突出显示“添加资源”选项并单击向下箭头。选择“添加现有文件”选项。现在,搜索您的字体文件,选择它,然后单击确定。保存“Resources.resx”文件。

在此处输入图像描述

3.) 创建一个函数(比如 InitCustomLabelFont() ),并在其中添加以下代码。

        //Create your private font collection object.
        PrivateFontCollection pfc = new PrivateFontCollection();

        //Select your font from the resources.
        //My font here is "Digireu.ttf"
        int fontLength = Properties.Resources.Digireu.Length;

        // create a buffer to read in to
        byte[] fontdata = Properties.Resources.Digireu;

        // create an unsafe memory block for the font data
        System.IntPtr data = Marshal.AllocCoTaskMem(fontLength);

        // copy the bytes to the unsafe memory block
        Marshal.Copy(fontdata, 0, data, fontLength);

        // pass the font to the font collection
        pfc.AddMemoryFont(data, fontLength);

您的自定义字体现已添加到 PrivateFontCollection。

4.) 接下来,将字体分配给您的标签,并在其中添加一些默认文本。

        //After that we can create font and assign font to label
        label1.Font = new Font(pfc.Families[0], label1.Font.Size);
        label1.Text = "My new font";

5.) 转到您的表单布局并选择您的标签。右键单击它并选择“属性”。查找属性“ UseCompatibleTextRendering ”并将其设置为“ True ”。

6.) 如有必要,您可以在确定字体不能再次使用后释放该字体。调用PrivateFontCollection.Dispose() 方法,然后您也可以安全地调用 Marshal.FreeCoTaskMem(data)。在应用程序的整个生命周期中,不打扰并让字体加载是很常见的。

7.) 运行您的应用程序。您现在应该看到已为给定标签设置了自定义字体。

干杯!

于 2014-05-07T14:04:43.887 回答
35

将字体作为资源嵌入(或仅将其包含在 bin 目录中),然后使用PrivateFontCollection加载字体(参见AddFontFileAddMemoryFont函数)。然后,您可以正常使用该字体,就像它安装在机器上一样。

PrivateFontCollection 类允许应用程序安装现有字体的私有版本,而无需替换字体的系统版本。例如,GDI+ 可以在系统使用的 Arial 字体之外创建 Arial 字体的私有版本。PrivateFontCollection 也可用于安装操作系统中不存在的字体。

来源

于 2009-08-25T18:15:05.743 回答
5

我认为解决方案是将所需的字体嵌入到您的应用程序中。

试试这个链接:

http://www.emoreau.com/Entries/Articles/2007/10/Embedding-a-font-into-an-application.aspx

于 2009-08-23T18:17:56.907 回答
4

添加您要使用的字体。

在此处输入图像描述

`

    PrivateFontCollection modernFont = new PrivateFontCollection();

    modernFont.AddFontFile("Font.otf");

    label.Font = new Font(modernFont.Families[0], 40);`

我也做了一个方法。

 void UseCustomFont(string name, int size, Label label)
    {

        PrivateFontCollection modernFont = new PrivateFontCollection();

        modernFont.AddFontFile(name);

        label.Font = new Font(modernFont.Families[0], size);


    }

在此处输入图像描述

于 2016-10-04T21:55:19.873 回答