You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms:从共享项目加载FontAwesome字体

实现Xamarin.Forms共享类库中FontAwesome字体的跨平台共享加载

很开心能帮你搞定这个字体共享的问题,其实不用自定义渲染器就能轻松实现,下面是一步步的操作指南:

1. 将字体文件嵌入共享类库

首先把你的fontawesome-webfont.ttf文件添加到共享类库中:

  • 在共享类库项目里新建一个文件夹,命名为Fonts(名字可自定义,但后续配置要对应上)
  • 把字体文件拖进这个文件夹
  • 选中字体文件右键打开属性:
    • 设置生成操作为Embedded Resource
    • 设置复制到输出目录为不复制(因为字体已经嵌入到程序集里,无需单独复制)

2. 在共享类库中定义全局字体资源

接下来在共享类库的资源文件里(比如App.xaml或者专门的Styles.xaml)添加字体的全局定义,覆盖各平台的加载路径:

<Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:Key="FontAwesome" x:TypeArguments="x:String">
            <!-- Android 平台:直接引用字体文件名 -->
            <On Platform="Android" Value="fontawesome-webfont.ttf#FontAwesome" />
            <!-- iOS 平台:使用文件名+字体家族名 -->
            <On Platform="iOS" Value="fontawesome-webfont.ttf#FontAwesome" />
            <!-- UWP 平台:使用嵌入式资源绝对路径,替换成你的类库程序集名称 -->
            <On Platform="UWP" Value="ms-appx:///MySharedLibrary/Fonts/fontawesome-webfont.ttf#FontAwesome" />
        </OnPlatform>

        <!-- 可选:定义通用样式,方便全项目复用 -->
        <Style x:Key="FontAwesomeIconStyle" TargetType="Label">
            <Setter Property="FontFamily" Value="{StaticResource FontAwesome}" />
            <Setter Property="FontSize" Value="20" />
        </Style>
    </ResourceDictionary>
</Application.Resources>

注意:把MySharedLibrary替换成你实际的共享类库程序集名称(在项目属性的“程序集名称”里查看)。另外,#后面的FontAwesome要和字体文件本身的家族名称一致,不确定的话可以右键字体文件在系统中打开,查看“详细信息”里的“字体名称”。

3. 在业务项目中引用共享类库资源

如果你的业务项目(UWP/Android/iOS)已经引用了这个共享类库,只需要在各自的App.xaml里合并共享类库的资源字典即可:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- 引用共享类库的资源文件,路径根据实际情况调整 -->
            <ResourceDictionary Source="ms-appx:///MySharedLibrary/Styles.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

4. 测试使用

现在你就可以在所有引用了共享类库的项目里直接使用FontAwesome字体了,比如:

<!-- 使用预定义样式 -->
<Label Text="&#xf007;" Style="{StaticResource FontAwesomeIconStyle}" />

<!-- 直接设置FontFamily -->
<Label Text="&#xf015;" FontFamily="{StaticResource FontAwesome}" FontSize="24" />

这样就能实现FontAwesome字体在所有Xamarin.Forms项目中共享,不用每个项目都重复拷贝字体文件啦!

内容的提问来源于stack exchange,提问作者DirtyNative

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:05:12