private int mIconInt = 0; private string mIconString = string.Empty; [Category("Appearance")] public int Icon { get { return mIconInt; } set { if (value != mIconInt) { mIconInt = value; //In FontAwesome, the code point "0xf0c7" is the "save" icon. mIconString = char.ConvertFromUtf32(value); } } } [Category("Appearance")] public float IconSize { get; set; } //Unit = em private static PrivateFontCollection Fonts { get; set; } //This object must live as long as it's fonts are in use. private static Font IconFont { get; set; } //Shared among all font icon buttons. private Font GetFont() { if (IconFont == null) { Fonts = new PrivateFontCollection(); if (File.Exists("FontIconAwesome.ttf")) { Fonts.AddFontFile("FontIconAwesome.ttf"); } if (Fonts.Families.Length > 0) { IconFont = new Font(Fonts.Families[0], IconSize > 0f ? IconSize : this.Font.Size); } } return IconFont; } protected override void OnPaint(PaintEventArgs e) { Font font = GetFont(); //Needs to be done before any painting goes on. if (font == null) { font = this.Font; } base.OnPaint(e); string text = IconFont != null && mIconInt > 0 ? mIconString : this.Text; Rectangle textArea = new Rectangle(1, 1, this.Width, this.Height); Brush textColor = ...; e.Graphics.DrawString(text, font, textColor, textArea); }
22 April 2015
.NET - Using a font file in a custom control
For my text editor project Filepad I came up with the idea to use a custom control that would use an icon font, like we often do these days in web projects. The obvious font choice is of course FontAwesome. I found initial assistance at this project, and some at MSDN.
It's actually pretty easy. Include the font file in the project and set it to copy to the output directory. The following is the relevant parts of the code of my control to make the font work. I provide the code point of the icon I want through a property that is then converted to a string. The code points for FontAwesome are listed here.
Labels:
.NET
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment