【问题标题】:Xamarin.Forms fontawesome works on UWP but shows square on AndroidXamarin.Forms fontawesome 适用于 UWP,但在 Android 上显示为正方形
【发布时间】:2017-06-07 09:06:45
【问题描述】:

我在我的 Xamarin.Forms 项目中添加了 fontawesome,在 UWP 上字体看起来符合预期,但在 android 上它是方形的。我已将 build-action 设置为 AndroidAsset 但它不起作用。

【问题讨论】:

  • 当文本字段中有一个字符并且该字符的值为 0xf000 或更高时,您是否将字体替换为 FontAwesome?

标签: xaml user-interface xamarin.android xamarin.forms font-awesome


【解决方案1】:

在 Android 上,使用 FontAwesome 有点麻烦。这篇文章后面的代码是关于如何以最简单的方式使用 Font Awesome。设置后就像使用标签一样简单。

我们使用自定义渲染器查看相关标签,确定文本字段中是否有一个字符以及该字符的值是否为0xf000 或更高。如果是这样,我们将字体替换为FontAwesome

由于图标都以0xf000 或更高开头,自定义渲染器将确保使用正确的字体

Reference article

[assembly: ExportRenderer(typeof(Label), typeof(AwesomeRenderer))]

namespace Awesome.Droid
{
    public class AwesomeRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var label = (TextView)Control;

            var text = label.Text;
            if(text.Length > 1 || text[0] < 0xf000)
            {
                return;
            }

            var font = Typeface.CreateFromAsset(Xamarin.Forms.Forms.Context.ApplicationContext.Assets, "fontawesome.ttf");
            label.Typeface = font;
        }
    }
}

【讨论】:

  • 谢谢!有用!希望它不需要 UWP 上的渲染器。很快我也将不得不在 iOS 上部署它,也许你知道 iOS 是否也需要自定义视图渲染器?
猜你喜欢
  • 2020-07-24
  • 2018-07-19
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
相关资源
最近更新 更多