如何在项目中使用Font Awesome图标作为ImageButton的图标

Got*_*atm 7 c# xaml xamarin font-awesome xamarin.forms

我在实现如何在 Xamarin 应用程序中使用 Font Awesome 图标时遇到问题,我想将其与ImageButton图标一起使用。我发现的大多数教程都无法帮助我理解它是如何工作的。

Cfu*_*fun 14

正如微软文档中所解释的:

  1. 您首先需要拥有我认为的字体文件.ttf(或.otf)。
  2. 将其添加到您的共享项目中。
  3. 右键单击该文件并单击“属性”,然后将其构建操作设置为Embedded Resource
  4. AssemblyInfo.cs在您的或中使用友好的别名将其导出App.xaml.cs

[assembly: ExportFont("file-name.ttf", Alias = "FontAwesome")]

  1. 消耗它:
<Label FontFamily="FontAwesome" Text="&#xf004;"/>
Run Code Online (Sandbox Code Playgroud)

有关图标代码列表,请查看FontAwesome 代码


如果您想将其与按钮等点击功能一起使用,则可以将标签与GestureRecognizers一起使用:

<Label FontFamily="FontAwesome" Text="&#xf004;">
     <Label.GestureRecognizers>
         <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
     </Label.GestureRecognizers>
</Label>
Run Code Online (Sandbox Code Playgroud)

更新

更好地使用ImageButton带有FontImageSource属性而不是标签的属性,您具有按钮的单击功能,我还发现有趣的是您可以更改字形图标的颜色,天气硬编码或动态取决于所选主题,这是一个示例:

<ImageButton>
    <ImageButton.Source>
        <FontImageSource FontFamily="FontAwesome"
                         Glyph="{x:Static fonts:IconFont.AddressBook}"
                         Color="{AppThemeBinding Dark=White,
                                                 Light=Black}"/>
    </ImageButton.Source>
</ImageButton>
Run Code Online (Sandbox Code Playgroud)

您还可以定义一个具有const string属性的静态类,每个属性都具有与图标字形相对应的代码作为值,并作为其名称的描述,这样您只需提供描述而不是像我那样提供代码Glyph="{x:Static fonts:IconFont.AddressBook}",它将看起来像这样:

 static class IconFont
    {
        public const string Ad = "\uf641";
        public const string AddressBook = "\uf2b9";
...
}
Run Code Online (Sandbox Code Playgroud)

我邀请您观看此视频教程并查看此 GitHub 页面,该页面从您提交的字体字形文件开始为您生成静态 C# 类。