问题
I am having a problem to realize how to use Font Awesome icons in my Xamarin application, I want to use it with ImageButton
as icon. And most tutorials I found didn't help me understand how it works.
回答1:
As explained in Microsoft Documentation:
- You need to first to have the font file I believe
.ttf
(or .otf). - Add it to your shared project.
- Right click on the file and click on "properties", then set it build action to Embedded Resource.
- Export it with a friendly alias name in your
AssemblyInfo.cs
orApp.xaml.cs
:
[assembly: ExportFont("file-name.ttf", Alias = "FontAwesome")]
- Consume it:
<Label FontFamily="FontAwesome" Text=""/>
For the list of icons code take a look at FontAwesome codes.
If you want to use it with click capabilities like a button, then you can use a label with GestureRecognizers:
<Label FontFamily="FontAwesome" Text="">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
</Label.GestureRecognizers>
</Label>
EDIT
Even better use an ImageButton
with a FontImageSource
property instead of a label, you have click capabilities of a button also I found interesting that you can change the color of your glyph icon, weather hard-coded or dynamically depending on the selected theme, here is an example:
<ImageButton>
<ImageButton.Source>
<FontImageSource FontFamily="FontAwesome"
Glyph="{x:Static fonts:IconFont.AddressBook}"
Color="{AppThemeBinding Dark=White,
Light=Black}"/>
</ImageButton.Source>
</ImageButton>
You can also define a static class having const string
properties, each one having as value the code corresponding to an icon glyph and as name a description of it that way you will need to provide only the description instead of the code like I did with Glyph="{x:Static fonts:IconFont.AddressBook}"
, it will looks something like this:
static class IconFont
{
public const string Ad = "\uf641";
public const string AddressBook = "\uf2b9";
...
}
I invite you to follow this video tutorial and check out this GitHub Page which generate the static c# class for you starting from a font glyph file that you submit.
来源:https://stackoverflow.com/questions/65095134/how-to-use-font-awesome-icons-in-project-as-an-icon-of-imagebutton