【发布时间】:2018-02-07 06:47:25
【问题描述】:
我正在使用一种字体在我的移动应用程序中显示图标。问题是,字体图标在我直接写入xaml文件时显示正确,但在运行时设置它不起作用。
我通过为每个平台创建自定义标签控件和自定义渲染器来实现字体图标。我在 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="" VerticalOptions="Center" HorizontalOptions="Center" FontSize="40" />
</StackLayout>
</ContentPage>
以下代码不起作用:
lblTestIcon.Text = "";
实施来源如下:
【问题讨论】:
-
您是否涵盖了您发布的文章中的第 5 步?我已经错过了几次这一步,它只是导致它无法找到字体包.... 步骤 5. 将您的自定义字体导入您的 Android 项目 右键单击您的 Android 项目中的 Assets 目录,然后选择“添加文件”。导航到您在硬盘驱动器上选择的字体文件并将其添加到项目中。添加文件后,右键单击它并检查“构建操作”是否设置为“AndroidAsset”。
-
使用文章中提到的以下代码解决了该问题,但不知何故我错过了它。文本 = System.Net.WebUtility.HtmlDecode("");
标签: android ios fonts xamarin.forms