Xamarin Forms: Font icon not getting rendered at run-time

自作多情 提交于 2020-01-15 12:49:08

问题


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="&#xe012;" VerticalOptions="Center" HorizontalOptions="Center" FontSize="40" />
    </StackLayout>

</ContentPage>

Following code doesn't work:

lblTestIcon.Text = "&#xe012;";

Source of the implementation is following:

https://blog.bitbull.com/2017/05/10/using-a-custom-icon-font-in-xamarin-forms/comment-page-1/#comment-1209


回答1:


The issue is fixed using following code which was told in the article but somehow I missed it.

Text = System.Net.WebUtility.HtmlDecode ("&#xe012;");

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;
}


来源:https://stackoverflow.com/questions/45945419/xamarin-forms-font-icon-not-getting-rendered-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!