Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 75885

FontAwesome Label: Here's how!

$
0
0

Here's how you'll use the new FontAwesome label (Any Graphic font will work, but FontAwesome is Awesome):

var coolLabel = new FontAwesomeIcon(FontAwesomeIcon.Icon.Gear)

Here's how to set it up.

Download the FontAwesome font and unzip it. Rename the ttf to FontAwesome.ttf. Note the Case of the name. Copy it to Android /Assets and mark as a BundleAsset. Copy to iOS /Resources and mark as BundleResource and "Copy Always". In iOS edit the info.plist and add this:

  <key>UIAppFonts</key>
  <string>FontAwesome.ttf</string>

Now that we have the font in our projects we need to tell Android, and ONLY Android how to get to the Font. Here's a renderer you can just drop in FontAwesomeIconRenderer.cs:

[assembly: ExportRenderer(typeof(FontAwesomeIcon), typeof(FontAwesomeIconRenderer))]

namespace AAA.Android.Renderers
{
    /// <summary>
    /// Add the FontAwesome.ttf to the Assets folder and mark as "Android Asset"
    /// </summary>
   public  class FontAwesomeIconRenderer: LabelRenderer
    {
       protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
       {
           base.OnElementChanged(e);
           if (e.OldElement == null)
           {
               //The ttf in /Assets is CaseSensitive, so name it FontAwesome.ttf
               Control.Typeface = Typeface.CreateFromAsset(Forms.Context.Assets, FontAwesomeIcon.Typeface + ".ttf");
           }
       }
    }
}

Here's the Label for your common UI project:

namespace AAA.Common.Views.Shared.FontAwesome
{
    public class FontAwesomeIcon : Label
    {
        //Must match the exact "Name" of the font which you can get by double clicking the TTF in Windows
        public const string Typeface = "FontAwesome";  

        public FontAwesomeIcon(string fontAwesomeIcon=null)
        {
            FontFamily = Typeface;    //iOS is happy with this, Android needs a renderer to add ".ttf"
            Text = fontAwesomeIcon;
        }

        /// <summary>
        /// Get more icons from http://fortawesome.github.io/Font-Awesome/cheatsheet/
        /// Tip: Just copy and past the icon picture here to get the icon
        /// </summary>
        public static class Icon
        {
            public static readonly string Gear = "";
            public static readonly string Globe = "";
        }
    }
}

Viewing all articles
Browse latest Browse all 75885

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>