FontAwesome Label: Here's how!

IanVinkIanVink CAInsider, University ✭✭✭

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 = "";
        }
    }
}
«1

Posts

  • IanVinkIanVink CAInsider, University ✭✭✭

    EDIT:

    in the iOS plist it should be an array, not a string:

     <key>UIAppFonts</key>
      <array>
        <string>FontAwesome.ttf</string>
      </array>
    
  • IanVinkIanVink CAInsider, University ✭✭✭

    I found a list of c# font awesome Unicode values.

    Source: https://github.com/neilkennedy/FontAwesome.Xamarin/blob/master/FontAwesome.Xamarin/FontAwesome.cs

               public static string Glass = "\uf000";
                public static string Music = "\uf001";
                public static string Search = "\uf002";
                public static string EnvelopeO = "\uf003";
                public static string Heart = "\uf004";
                public static string Star = "\uf005";
    

    etc.....

  • IanVinkIanVink CAInsider, University ✭✭✭

    Here's a list of "Font Awesome - like" graphic fonts. Consider using fonts icons instead of PNGs, your app will be smaller and the graphics rendering clean as they are vector based.

    http://fontello.com/

  • VictorHGarciaVictorHGarcia USUniversity ✭✭

    Pretty awesome! I was wondering why the implementation was not working on Android. This solved my problem. Thank you.

    However in another question: I have Tabbed Page, I know there is an icon property on each page and it will use it as icon, however, how can use Font-Awesome to assign an icon to the tabbed page?

    Any help or workaround is welcome.

    Note: I'm using Xamarin.Forms 1.3.1 stable version

  • ChaseFlorellChaseFlorell CAInsider, University mod

    If memory serves me right, you cannot (out of the box) use FontAwesome as a TabbedPage icon. It's venturing into Custom Renderer land.

  • IanVinkIanVink CAInsider, University ✭✭✭

    I agree with @ChaseFlorell‌ . You can put images there though it's a custom tab rendering job.

  • LukeWatsonLukeWatson USUniversity ✭✭

    Hi,

    i was having an issue using font awesome / custom renderer.

    i had a label that is using the font awesome renderer on android and it works flawlessly... except

    i have a type converter that is changing the 'icon' (or text) based on a binding. i.e. When true set text to show icon A, when false show icon B. The type converter is not really relevant here except it may be how others implement this too.

    The problem i was having is that when the observable property changes everything gets kicked off, but the icon is never rendered. i tried changing the text to some actual text (not special chars) and this works, but it seems that the custom renderer is not running again.

    I see that we are overriding OnElementChanged.. so i tried OnElementPropertyChanged and this seemed to fix the problem.

     protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            {
                base.OnElementPropertyChanged(sender, e);
                if (e.PropertyName == "Text")
                    Control.Typeface = Typeface.CreateFromAsset(Context.Assets, "fonts/" + FontAwesomeIcon.Typeface + ".ttf");
            }
    

    anyone see any problems / performance issues?

  • SimonTaylor.2787SimonTaylor.2787 AUMember ✭✭

    I'm having an issue when a FontAwesomeIcon is placed in a custom ViewCell in a ListView. On first display the icon appears, but when the cell is scrolled off the screen then back on it is sometimes blank.

    I've tried setting the typeface in a bunch of the other events on the custom renderer with no effect. In the debugger the events are firing. Any ideas?


    public class FontAwesomeIconRenderer : LabelRenderer
    {
    private static Typeface _Typeface;

        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                this.SetTypeface();
            }
        }
    
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == "Text")
            {
                this.SetTypeface();
            }
        }
    
        protected override void OnDisplayHint(int hint)
        {
            base.OnDisplayHint(hint);
            if (hint == (int)Android.Views.SystemUiFlags.Visible)
            {
                this.SetTypeface();
            }
        }
    
        protected override void OnDraw(Canvas canvas)
        {
            this.SetTypeface();
            base.OnDraw(canvas);
        }
    
        protected override void OnRestoreInstanceState(IParcelable state)
        {
            this.SetTypeface();
            base.OnRestoreInstanceState(state);
        }
    
        protected override void OnAttachedToWindow()
        {
            this.SetTypeface();
            base.OnAttachedToWindow();
        }
    
        protected override void OnVisibilityChanged(Android.Views.View changedView, ViewStates visibility)
        {
            this.SetTypeface();
            base.OnVisibilityChanged(changedView, visibility);
        }
    
        private void SetTypeface()
        {
            if (_Typeface == null)
            {
                //The ttf in /Assets is CaseSensitive, so name it FontAwesome.ttf
                _Typeface = Typeface.CreateFromAsset(Forms.Context.Assets, FontAwesomeIcon.Typeface + ".ttf");
            }
    
            this.Control.Typeface = _Typeface;
        }
    

  • SimonTaylor.2787SimonTaylor.2787 AUMember ✭✭

    I fixed this by always setting the Typeface in OnElementChanged.

  • DungNguyen.7054DungNguyen.7054 USMember

    Thanks for the tut, it worked very well. But I have a problem. When I change font attribute of the label to bold like this:
    myLabel.FontAttributes = FontAttributes.Bold;
    The icon become a rectangle with a "?" in it. Do you know how to fix this?

  • nbevansnbevans USMember ✭✭✭

    FontAwesome doesn't have bold styles.

  • DungNguyen.7054DungNguyen.7054 USMember

    Thanks @nbevans , I want to know how to set font for bold style in Xamarin Forms, so that I can set the normal FontAwesome for bold style, I don't need bold FontAwesome. Is there a solution?

  • nbevansnbevans USMember ✭✭✭

    Not likely an easy one. Maybe if you dig into the depths of platform specific renderers you can find some way to redirect the bold style back to the normal style. But I can only imagine that type of functionality on Android. WP and iOS are too "follow the golden path" to allow something like that.

    Why not investigate using a font editor to modify the FontAwesome TTF file and repoint the bold styles to the normal styles?

  • JohnWilson.4976JohnWilson.4976 AUMember ✭✭

    I was setting these in a ListView as well and the only way I could get them to come up more consistently was to do what @LukeWatson did and use the OnElementProperty changed as well. I say "more consistently" because I also had to add a reference and usage to the FontAwesomeIconRenderer because it was being compiled/linked out of the Android app. It started behaving a bit better (at least under debugging) when I added a

    var fontAwesomeIconRenderer = new FontAwesomeIconRenderer();
    

    Just after the Forms.Init(this, bundle) line in the MainActivity.

  • JoaquinGrechJoaquinGrech ESMember ✭✭

    @DungNguyen.7054 I just came across this post, maybe this helps... replace the Control.Typeface = x
    with
    Control.SetTypeface(typeface, TypefaceStyle.Normal);
    and also TypefaceStyle.Bold
    it will render the same font but it won't fail if you change it to bold

  • PedroNeves.7715PedroNeves.7715 USMember ✭✭

    What about in Windows/WP and iOS?

  • BuhhSathBuhhSath USMember ✭✭

    Listview Perfomance issue.

  • CherubyxCherubyx CAUniversity ✭✭

    @LukeWatson Thank you, your solution helped me out tremendously after hours of looking around!

  • L4rSL4rS CHMember ✭✭

    Hi, does somebody have an idea why a Label with a binding property can't be renderer as a fontawesome? See here: https://forums.xamarin.com/discussion/30298/fontfamily-not-working-when-using-textproperty-binding

  • JMarcusJMarcus USMember ✭✭✭

    Check out the Iconize - FontAwesome nuget package: https://www.nuget.org/packages/Xam.Plugin.Iconize.FontAwesome/

  • L4rSL4rS CHMember ✭✭
    edited January 2016

    @JMarcus Thank you so much! It works fine! But how can I set the size of the Icon? If I set it by e.g. HeightRequest it's getting blurred.

  • JMarcusJMarcus USMember ✭✭✭

    @L4rS you can set it in the text. ex: {fa-500px 14px}

  • L4rSL4rS CHMember ✭✭

    @JMarcus thx!

  • MarkErickson.91MarkErickson.91 USMember ✭✭
    edited July 2016

    @JMarcus I just started using Iconize and I'm getting question marks with borders. I'm assuming I'm missing something but not sure what. This is a XF project. I installed latest version 1.0.10. (Xam.FormsPlugin.Iconize, Xam.Plugin.Iconize, Xam.Plugin.Iconize.FontAwesome to the iOS project) and same minus the .FontAwesome to the PCL project.

    I have this working in a standalone "proof of concept" solution. The only difference is in the real solution I'm binding the value for "Icon" (ImageIcon). I am using a "hard coded" icon (fa-circle) and that too is rendering a question mark with a border.

    Thanks for any direction/help

  • MarilouMarilou PHMember ✭✭

    @Mabu said:
    @IanVink Can you explain how to use font awesome in xaml?

    I have the same question. Anyone have any idea how this is used in XAML?

  • For anyone who stumbles upon this post:
    Extend the FontAwesomeIcon class with a default constructor without any parameters.

    Like this:

    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";
    
            //Constructor for XAML use
            //<local:FontAwesomeIcon Text="{x:Static local:FontAwesomeIcon.Icon.Gear}"></local:FontAwesomeIcon>
            public FontAwesomeIcon()
            {
                FontFamily = Typeface;
            }
    
            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 https://github.com/neilkennedy/FontAwesome.Xamarin/blob/master/FontAwesome.Xamarin/FontAwesome.cs
            /// </summary>
            public static class Icon
            {
                public static string Search = "\uf002";
                public static string Plus = "\uf067";
            }
        }
    

    Then you can use it in Xaml like this:

    <local:FontAwesomeIcon Text="{x:Static local:FontAwesomeIcon.Icon.Gear}"></local:FontAwesomeIcon>
    

    remember to add the "local" namespace to the xaml:

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
                            xmlns:local="clr-namespace:TestProject;assembly=TestProject"
                    x:Class="TestProject.SettingsPage"
                    Title="Settings">
    
  • abdoelzamalkawyabdoelzamalkawy EGMember ✭✭✭

    hello
    does any one can solve my problem here

    https://forums.xamarin.com/discussion/comment/271734

    thanks

  • gustavolima.7435gustavolima.7435 USMember ✭✭

    @michael_lopez said:
    For anyone who stumbles upon this post:
    Extend the FontAwesomeIcon class with a default constructor without any parameters.

    Like this:

    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";
    
          //Constructor for XAML use
          //<local:FontAwesomeIcon Text="{x:Static local:FontAwesomeIcon.Icon.Gear}"></local:FontAwesomeIcon>
          public FontAwesomeIcon()
          {
              FontFamily = Typeface;
          }
    
          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 https://github.com/neilkennedy/FontAwesome.Xamarin/blob/master/FontAwesome.Xamarin/FontAwesome.cs
          /// </summary>
          public static class Icon
          {
              public static string Search = "\uf002";
              public static string Plus = "\uf067";
          }
      }
    

    Then you can use it in Xaml like this:

    <local:FontAwesomeIcon Text="{x:Static local:FontAwesomeIcon.Icon.Gear}"></local:FontAwesomeIcon>
    

    remember to add the "local" namespace to the xaml:

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
                          xmlns:local="clr-namespace:TestProject;assembly=TestProject"
                  x:Class="TestProject.SettingsPage"
                  Title="Settings">
    

    I'm getting this error with the x:Static


    Unhandled Exception:

    Xamarin.Forms.Xaml.XamlParseException: Position 15:30. Type FontAwesomeIcon.Icon not found in xmlns clr-namespace:MyProject.Controls;

  • KiloKilo USMember

    I got that error too but was able to solve it by moving the static class outside of the nested FontAwesome label class.

    It seems like xaml does not like accessing nested classes.
    https://stackoverflow.com/questions/40103573/cant-set-properties-on-nested-classes-from-xaml

    On another note i can't seem to get it to display anything. I just keep getting that stupid question mark symbol.

  • RicardoMedinaRicardoMedina USMember ✭✭

    Does anyone has a Xamarin Forms Hello World sample with this?

  • csampaio01csampaio01 PTMember ✭✭✭
    edited October 2017

    Anyone used simple line icons?

  • ValoramaValorama USMember ✭✭
    edited February 2018

    John the FontAwesome Label worked great, displays my icon on device. But now I'm trying to implement the "stylish" version following your example, but when I deploy app onto my android device, the icon doesn't display. I have verified that InitializeComponent() is called in my App() constructor, and I have added the ResourceDictionary to the App.xaml.

    Is there anything else I'm possibly missing for the Binding FontAwesome to work?

    [SOLVED] - In the XAML change the style to use StaticResource instead of Binding and the icon displays perfectly!

  • SolomonFriedSolomonFried USMember ✭✭

    Thanks John. I had already created my own FontIcon class along with a custom renderer on Android. I have replaced it with your solution and created 4 styles for 4 different custom fonts that I use. (mostly "Font Awesome 5 Pro" and "Font Awesome 5 Pro Solid".

    Also user Valorama's suggestion of using {static resource} instead of {binding}

    Very elegant solution.
    I suppose I can use this on any control that references a FontFamily.

    Now all we need is a way to keep only one set of icon files in the main shared project and have the build process take care of distributing them.
    Thanks

  • jorge_tinocojorge_tinoco Member ✭✭

    @JohnTolle, Gorilla SDK is kind of app?
    I use Gorilla Player, and certainly crashed when implementing fontawesome icons. After following instructions in "Gorilla SDK" I´m not getting work gorilla player

  • amirvenusamirvenus USMember ✭✭✭

    @JohnTolle said:
    I'm not sure when it was added, but custom fonts (including icon fonts like Font Awesome) can be used natively in Xamarin Forms with no code needed:
    https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/#Using_a_Custom_Font

    For example:
    1. Add FontAwesome.otf to your Assets folder
    2. Set it to Build Action of AndroidAsset
    3. Set the Copy to Output Directory to Copy if Newer
    4. Start using it in your XAML:

    <Label Text="&#xF070;">
      <Label.FontFamily>
          <OnPlatform x:TypeArguments="x:String">
              <On Platform="iOS" Value="FontAwesome" />
              <On Platform="Android" Value="FontAwesome.otf#FontAwesome" />
              <On Platform="UWP, WinRT, WinPhone" Value="Assets/Fonts/FontAwesome.otf#FontAwesome" />
          </OnPlatform>
      </Label.FontFamily>
    </Label>
    

    Yes, you'll need a character viewer (I use the UWP app named simply Character Map) to find the right icons and their lovely hex codes, but it's a pretty clean thing.

    You can even get "stylish" and make things more reusable on your XAML page:

    <Label Style="{Binding FontAwesome}" Text="&#xF070;"/>
    

    With the following Style in your favorite <ResourceDictionary>:

    <OnPlatform x:Key="FontAwesomeString" x:TypeArguments="x:String">
      <On Platform="iOS" Value="FontAwesome" />
      <On Platform="Android" Value="FontAwesome.otf#FontAwesome" />
      <On Platform="UWP, WinRT, WinPhone" Value="Assets/Fonts/FontAwesome.otf#FontAwesome" />
    </OnPlatform>
    <Style x:Key="FontAwesome" TargetType="Label">
      <Setter Property="FontFamily" Value="{StaticResource FontAwesomeString}" />
    </Style>
    

    For those of you using Gorilla Player to preview your pages, you'll need to use the Gorilla SDK as the regular player crashes if you try to use custom fonts.

    For those of you using Xamarin Live Player, yeah... um... I don't know how to make custom fonts work, so if someone else knows how, please share with the rest of the class!

    It works perfectly fine on Android but on iOS it shows a question mark.

  • KlinguKlingu USMember ✭✭
    edited June 2018

    People, I got a problem implementing the Font Awesome 5
    In the Xaml Preview viewer I see the Share Symbol.

    But on the iPhone Device I see [?] (On Android it is showing the Share Icon as expected)

    My App.Xaml.cs code:

        Current.Resources = new ResourceDictionary();
        // Font awesome
        App.Current.Resources["FontawesomeSolid"] = Device.RuntimePlatform == Device.iOS ? "Font Awesome 5 Free" : "fa-solid-900.ttf#Font Awesome 5 Free";
    
        Current.Resources.Add("RicoShareLabel", new Style(typeof(Label))
        {
                Setters =
                {
                    new Setter { Property = Label.TextColorProperty, Value = RicoColors.White},
                    new Setter { Property = View.HorizontalOptionsProperty, Value = LayoutOptions.End},
                    new Setter { Property = View.VerticalOptionsProperty, Value = LayoutOptions.Center},
                    new Setter { Property = AbsoluteLayout.LayoutBoundsProperty, Value = new Rectangle (0.97, 0.5, 0.2, 1)},
                    new Setter { Property = AbsoluteLayout.LayoutFlagsProperty, Value = AbsoluteLayoutFlags.All},
                    new Setter { Property = Label.FontSizeProperty, Value = 30},
                    new Setter { Property = Label.FontFamilyProperty, Value = Current.Resources["FontawesomeSolid"] }
                }
        });
    

    My WebViewPage.Xaml code

        <?xml version="1.0" encoding="UTF-8"?>
        <ContentPage
            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:localColors="clr-namespace:MyApp.Cross.Infrastructure"
            xmlns:helpers="clr-namespace:MyApp.Cross.Helpers;assembly=MyApp"
            x:Class="MyApp.Cross.Views.BlogFeedDetailView">
            <ContentPage.Content>
                <AbsoluteLayout
                    Style="{StaticResource RicoBaseAbsoluteLayout}"
                    IsEnabled="{Binding IsBusy, Converter={StaticResource BoolConverter}}">
                    <WebView
                        x:Name="Browser"
                        AbsoluteLayout.LayoutBounds="0,0,1,0.93"
                        AbsoluteLayout.LayoutFlags="All" />
                    <AbsoluteLayout
                        AbsoluteLayout.LayoutBounds="0,1,1,0.07"
                        AbsoluteLayout.LayoutFlags="All"
                        BackgroundColor="{x:Static localColors:Constants.RicoOrange} ">
                       <Label
                            Text="&#xf1e0;"
                            Style="{StaticResource RicoShareLabel}" >
                        </Label>
                    </AbsoluteLayout>
                </AbsoluteLayout>
            </ContentPage.Content>
            <ContentPage.Resources>
                <ResourceDictionary>
                    <helpers:InvertBoolConverter
                        x:Key="BoolConverter" />
                </ResourceDictionary>
            </ContentPage.Resources>
        </ContentPage>
    

    My Info.plist has

        <key>UIAppFonts</key>
            <array>
                <string>Fonts/Khula-Bold.ttf</string>
                <string>Fonts/Khula-ExtraBold.ttf</string>
                <string>Fonts/Khula-Light.ttf</string>
                <string>Fonts/Khula-Regular.ttf</string>
                <string>Fonts/Khula-Semibold.ttf</string>
                <string>Fonts/fa-brands-400.ttf</string>
                <string>Fonts/fa-regular-400.ttf</string>
                <string>Fonts/fa-solid-900.ttf</string>
                <string>Fonts/IndieFlower.ttf</string>
            </array>
    

    All the Font files (*.ttf) are located in "Resources/Fonts/"
    Build action = BundleResource
    Copy to output directory = Do not copy (Copy if newer does not make a differ)

    All the other Fonts I've used do work fine on iOS and Android.
    Where did I mis a thing...

    Thanks, Jeffrey

    [SOLVED!] I've removed the fa-brands-400.ttf and fa-regular-400.ttf and the references on the Info.plist and it's showing the share icon :)

    I think the issue is that these 2 files do have the same font name, and this conflicts in the rendering...

Sign In or Register to comment.