I'm using a font to display icons in my mobile app. The problem is, font icon is displayed correctly when I write it directly into xaml file but it doesn't work when I set it at runtime.
I have implemented the font icon by creating a Custom Label control and a Custom Renderer for each platform. I'm facing this problem on Android, haven't yet checked on iOS.
Custom Label:
using System;
using Xamarin.Forms;
namespace fonticon
{
public class IconLabel:Label
{
public IconLabel()
{
}
}
}
Custom renderer for Android:
using System;
using Android.Graphics;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
// This informs the compiler that we're using this class to render an IconLabel on this platform
[assembly: ExportRenderer(typeof(fonticon.IconLabel), typeof(fonticon.Droid.IconLabelRenderer))]
namespace fonticon.Droid
{
public class IconLabelRenderer:LabelRenderer
{
// sets the font for the platform-specific ui component to be our custom font
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
// Note we're using the filename here, NOT the font family name
var font = Typeface.CreateFromAsset(Forms.Context.ApplicationContext.Assets, "flatuiicons.ttf");
Control.Typeface = font;
}
}
}
Following XAML works:
<?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:local="clr-namespace:fonticon"
x:Class="fonticon.fonticonPage">
<StackLayout x:Name="mainContainer">
<local:IconLabel x:Name="lblTestIcon" Text="" VerticalOptions="Center" HorizontalOptions="Center" FontSize="40" />
</StackLayout>
</ContentPage>
Following code doesn't work:
lblTestIcon.Text = "";
Source of the implementation is following: