Reputation: 126
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:
Upvotes: 1
Views: 613
Reputation: 3626
I wrote a blog on using font images you might find interesting and more modern than this approach.
Upvotes: 0
Reputation: 126
The issue is fixed using following code which was told in the article but somehow I missed it.
Text = System.Net.WebUtility.HtmlDecode ("");
Also, added following code to the Android Custom Renderer:
// sets the font for the platform-specific ui component to be our custom font
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, 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;
}
Upvotes: 0