2017-08-29 33 views
1

我正在使用字体在我的移动应用程序中显示图标。问题是,当我将它直接写入xaml文件时,字体图标显示正确,但在运行时将其设置为不起作用。Xamarin表单:字体图标在运行时不会呈现

我已经通过为每个平台创建自定义标签控件和自定义渲染器来实现字体图标。我在Android上面临这个问题,还没有在iOS上进行检查。

自定义标签:

using System; 
using Xamarin.Forms; 

namespace fonticon 
{ 
    public class IconLabel:Label 
    { 
     public IconLabel() 
     { 
     } 
    } 
} 

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

下面的XAML工作:

<?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> 

下面的代码无法正常工作:实施

lblTestIcon.Text = "&#xe012;"; 

来源是以下几点:

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

+0

您已覆盖从文章第5步你贴?我已经错过了这一步几次,它只是导致它无法找到字体包.... 第5步。导入您的自定义字体到您的Android项目 右键单击您的资产目录在您的Android项目并选择“添加文件”。导航到您在硬盘上选择的字体文件并将其添加到项目中。添加文件后,右键单击它并选中“Build Action”设置为“AndroidAsset”。 –

+0

这个问题是通过使用文章中提到的以下代码修复的,但不知何故,我错过了它。 Text = System.Net.WebUtility.HtmlDecode(“&#xe012;”); – dsakpal

回答

0

的问题是使用下面的代码被告知的文章,但不知何故固定我错过了。

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

此外,添加以下代码到Android自定义呈现:

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