本文介绍了Xamarin形式:字体图标无法在运行时呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一种字体在我的移动应用程序中显示图标.问题是,当我将字体图标直接写入xaml文件时,它会正确显示,但是在运行时设置它却无法正常工作.

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.

我已经通过为每个平台创建自定义标签"控件和自定义渲染器"来实现字体图标.我在Android上遇到了这个问题,尚未在iOS上检查过.

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.

自定义标签:

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

推荐答案

使用下面的代码解决了该问题,该代码已在本文中讲述,但不知何故我错过了.

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

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

此外,还向Android自定义渲染器添加了以下代码:

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

这篇关于Xamarin形式:字体图标无法在运行时呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 13:47