xamarin.forms - 如何在 xamarin 表单的工具栏项中添加字体图标

标签 xamarin.forms android-toolbar

我在我的应用程序中使用了导航页面。我必须将字体图标设置为工具栏项目。但它显示十字符号,因为我没有设置字体系列。所以任何人都建议我在工具栏项中设置字体图标是否可行。

最佳答案

使用 Xamarin Forms 4.x(如果我没记错版本的话),他们添加了一个可以在 ToolbarItems 上使用的 FontImageSource 类型。你需要做的几件事...

将字体文件添加到您的平台项目。在 Android 上,将它们添加到 Assets 文件夹中,并将构建操作设置为 AndroidAsset。在 iOS 上,将它们添加到 Resources 文件夹中,并将构建操作设置为 BundleResource。同样在 iOS 上,编辑您的 info.plist 并添加

<key>UIAppFonts</key>
<array>
    <string>fontname.ttf</string>
    <string>fontname2.ttf</string>
    ...
</array>

现在 Xamarin 可以使用这些字体了。

我定义了一些应用程序资源来轻松加载字体:
<OnPlatform x:Key="FontAwesomeLightFontFamily" x:TypeArguments="x:String">
  <On Platform="Android" Value="fa-light-300.ttf#Font Awesome 5 Pro Light" />
  <On Platform="iOS" Value="FontAwesome5Pro-Light" />
</OnPlatform>
<OnPlatform x:Key="FontAwesomeRegularFontFamily" x:TypeArguments="x:String">
  <On Platform="Android" Value="fa-regular-400.ttf#FontAwesome5ProRegular" />
  <On Platform="iOS" Value="FontAwesome5ProRegular" />
</OnPlatform>
<OnPlatform x:Key="FontAwesomeSolidFontFamily" x:TypeArguments="x:String">
  <On Platform="Android" Value="fa-solid-900.ttf#FontAwesome5ProSolid" />
  <On Platform="iOS" Value="FontAwesome5ProSolid" />
</OnPlatform>

它位于合并到 App.xaml 资源中的资源字典中。

现在,当我想使用字体图标作为工具栏图标图像源时,我可以执行以下操作:
<Page.ToolbarItems>
  <ToolbarItem Command="{Binding SomeCommand}">
    <ToolbarItem.IconImageSource>
      <FontImageSource
        FontFamily="{StaticResource FontAwesomeSolidFontFamily}"
        Glyph="{x:Static fonts:FontAwesomeIcon.Cog}"
        Size="{StaticResource ToolbarIconImageSourceSize}" />
    </ToolbarItem.IconImageSource>
  </ToolbarItem>
</Page.ToolbarItems>

如果你想要一个静态类来定义字形图标而不是必须输入 unicode(我在上面字形中使用的 FontAwesomeIcon 类),在 https://andreinitescu.github.io/IconFont2Code/ 有一个很棒的工具这将根据上传的字体文件生成一个 C# 静态类。它最终看起来像
public static class FontAwesomeIcon
{
  public const string Abacus = "\uf640";
  public const string Ad = "\uf641";
  public const string AddressBook = "\uf2b9";
  public const string AddressCard = "\uf2bb";
  public const string Adjust = "\uf042";
  public const string AirFreshener = "\uf5d0";
  ...
}

关于xamarin.forms - 如何在 xamarin 表单的工具栏项中添加字体图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57395091/

相关文章:

xamarin.forms - 找不到 'MaxLength' 的属性、可绑定(bind)属性或事件,或者值和属性之间的类型不匹配

xamarin - 在XF中是否可以使用luberda-molinet/FFImageLoading代码替代svg图像

c# - 在运行时更改 xamarin.forms 颜色

android - 菜单项未显示为操作 android.support.v7.widget.Toolbar

Android 工具栏覆盖内容

java - 在同一 Activity 中从工具栏搜索 View 获取查询字符串?

android - 通过 fragments 在 recyclerview 和 toolbar 之间共享元素

visual-studio - 标签栏未显示在 TabbedPage 上

xamarin.forms - 使用Webview显示付款页面是否解决了应用商店的应用内购买问题?

android - 如何使用工具栏在底部显示操作项