【问题标题】:WinForm not work properly with fonts embedded resourcesWinForm 无法与字体嵌入资源一起正常工作
【发布时间】:2017-02-17 22:45:54
【问题描述】:

嵌入的资源字体在控件上无法正常工作。

但它可以被Graphics对象用来绘制一些东西。


  1. 首先,添加带有嵌入资源的fontawesome-webfont.ttf字体文件。

  2. 然后,从程序集资源中获取字体。

  3. 接下来,将字体属性分配给控件。

代码在这里:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Sample
{
    public partial class FormSample : Form
    {
        PrivateFontCollection pfc;
        Font font ;

        public FormSample()
        {
            InitializeComponent();
            pfc = LoadFontFromResource("Sample.assets.fontawesome-webfont.ttf");
            font = new Font(pfc.Families[0], 16, FontStyle.Regular);
            this.textBoxControl1.Text = "\uf028 fontawesome";
            this.label1.Text = "\uf028 fontawesome";
            this.label1.ForeColor = Color.Green;
            this.textBoxControl1.ForeColor = Color.Green;
            this.label1.Font = font;
            this.textBoxControl1.Font = font;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.label1.Font = font;
            this.textBoxControl1.Font = font;

            Graphics g = this.CreateGraphics();

            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;

            g.DrawString("\uf028 fontawesome(GDI+)", font, new SolidBrush(Color.Green), new Point(this.label1.Location.X+10, 80));
            g.Dispose();
        }

        /// <summary>
        /// Loads the font from resource.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns>PrivateFontCollection.</returns>
        public static PrivateFontCollection LoadFontFromResource(string name)
        {
            PrivateFontCollection pfc = new PrivateFontCollection();

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream stream = assembly.GetManifestResourceStream(name))
            {
                if (stream == null) return null;

                byte[] fontData = new byte[stream.Length];
                stream.Read(fontData, 0, (int)stream.Length);

                IntPtr ptr = Marshal.AllocHGlobal(fontData.Length);
                Marshal.Copy(fontData, 0, ptr, fontData.Length);

                pfc.AddMemoryFont(ptr, fontData.Length);

                return pfc;
            }
        }
    }
}

【问题讨论】:

  • 你能把这个表格的相关代码贴出来吗?并准确解释什么不能正常工作?

标签: winforms


【解决方案1】:

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多