我的Winform上有一个标签,我想使用一种名为XCalibur的自定义字体,使其显得更加时髦.
如果我在标签上使用自定义字体,然后构建解决方案,然后.ZIP\bin\Release中的文件,最终用户会看到我使用的自定义应用程序的标签,无论他们是否安装了该字体?
如果不是这样,那么在Labels.Text上使用自定义字体的正确方法是什么?
Sid*_*ant 37
通过查看可能的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);
Run Code Online (Sandbox Code Playgroud)
您的自定义字体现已添加到PrivateFontCollection中.
4.)接下来,将字体分配给Label,并在其中添加一些默认文本.
//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";
Run Code Online (Sandbox Code Playgroud)
5.)转到表单布局并选择标签.右键单击它并选择" 属性 ".查找属性" UseCompatibleTextRendering "并将其设置为" True ".
6.)如果有必要,您可以在确定它永远不会再次使用后释放字体.调用PrivateFontCollection.Dispose()方法,然后您也可以安全地调用Marshal.FreeCoTaskMem(数据).很常见的是不打扰并在应用程序的生命周期中加载字体.
7.)运行您的应用程序.您现在将看到已为给定标签设置了自定义字体.
干杯!
Ada*_*hes 26
将字体嵌入为资源(或仅将其包含在bin目录中),然后使用PrivateFontCollection加载字体(请参阅AddFontFile和AddMemoryFont函数).然后,您通常使用与机器上安装的字体相同的字体.
PrivateFontCollection类允许应用程序安装现有字体的私有版本,而无需替换字体的系统版本.例如,除了系统使用的Arial字体之外,GDI +还可以创建Arial字体的私有版本.PrivateFontCollection还可用于安装操作系统中不存在的字体.
添加您要使用的字体。
`
PrivateFontCollection modernFont = new PrivateFontCollection();
modernFont.AddFontFile("Font.otf");
label.Font = new Font(modernFont.Families[0], 40);`
Run Code Online (Sandbox Code Playgroud)
我也做了一个方法。
void UseCustomFont(string name, int size, Label label)
{
PrivateFontCollection modernFont = new PrivateFontCollection();
modernFont.AddFontFile(name);
label.Font = new Font(modernFont.Families[0], size);
}
Run Code Online (Sandbox Code Playgroud)
我认为解决方案是将所需的字体嵌入到您的应用程序中.
试试这个链接:
http://www.emoreau.com/Entries/Articles/2007/10/Embedding-a-font-into-an-application.aspx
| 归档时间: |
|
| 查看次数: |
36207 次 |
| 最近记录: |