Lad*_*ssa 9 c# visual-studio winforms
我使用以下代码添加了自定义字体:
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("C:\\Path To\\YourFont.ttf");
label1.Font = new System.Drawing.Font(pfc.Families[0], 16, FontStyle.Regular);
Run Code Online (Sandbox Code Playgroud)
我在资源中添加了字体文件.如何addFontFile从资源中添加?
sky*_*dev 10
private static void AddFontFromResource(PrivateFontCollection privateFontCollection, string fontResourceName)
{
var fontBytes = GetFontResourceBytes(typeof (App).Assembly, fontResourceName);
var fontData = Marshal.AllocCoTaskMem(fontBytes.Length);
Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length);
privateFontCollection.AddMemoryFont(fontData, fontBytes.Length);
// Marshal.FreeCoTaskMem(fontData); Nasty bug alert, read the comment
}
private static byte[] GetFontResourceBytes(Assembly assembly, string fontResourceName)
{
var resourceStream = assembly.GetManifestResourceStream(fontResourceName);
if (resourceStream == null)
throw new Exception(string.Format("Unable to find font '{0}' in embedded resources.", fontResourceName));
var fontBytes = new byte[resourceStream.Length];
resourceStream.Read(fontBytes, 0, (int)resourceStream.Length);
resourceStream.Close();
return fontBytes;
}
Run Code Online (Sandbox Code Playgroud)
如果您在资源中包含您的字体
试试这个功能
private void addfontfrommemory()
{
Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("yourfont.ttf");
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata,0,(int)fontStream.Length);
fontStream.Close();
unsafe
{
fixed(byte * pFontData = fontdata)
{
pfc.AddMemoryFont((System.IntPtr)pFontData,fontdata.Length);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
如何从程序集加载资源:(YourNamespace.file.ttf)
Stream fontStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("WindowsFormsApplication1.SBADR.TTF");
Run Code Online (Sandbox Code Playgroud)
我的解决方案探索者:

小智 5
我就是这样做的。
首先获取 Font.ttf 文件并使用 Visual Studio 将文件拖放到根文件夹或资源文件夹中。
在解决方案资源管理器中,右键单击该文件,然后单击属性。选择Build Action = Content。这将在项目属性 > 发布 > 应用程序文件下的应用程序文件中显示该文件。您将看到现在可以选择该文件(默认情况下会自动包含该文件)。
ClickOnce 现在会将文件复制到StartupPath
要使用它,请遵循以下示例:
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(Path.Combine(Application.StartupPath, "font_name.ttf"));
textBox1.Font = new Font(pfc.Families[0], 18, FontStyle.Regular);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20589 次 |
| 最近记录: |