如何在Xamarin.Forms中更改标签的字体系列

时间:2018-10-07 14:48:17

标签: xamarin xamarin.forms xamarin.android

我尝试使用CSS和XAML更改标签的字体系列,但是字体没有反映出来。我正在尝试在我的应用程序中使用Montserrat字体。我该如何解决?

XAML代码:

<Label StyleClass="label" Text="Sample"/>

CSS代码:

.label{
    font-family: Montserrat;
}

2 个答案:

答案 0 :(得分:2)

为了在项目中使用自定义字体,您必须执行以下操作:

在您的Android项目中,将字体文件放置在Assets文件夹中,并确保构建类型为AndroidAsset。

然后,您可以在XAML中在资源字典中声明字体(例如,在App.xaml中

<ResourceDictionary>
    <OnPlatform x:TypeArguments="x:String" x:Key="BoldFont">
        <On Platform="Android" Value="OpenSans-Bold.ttf#Open Sans" />
        <On Platform="UWP" Value="/Assets/OpenSans-Bold.ttf#Open Sans" />
        <On Platform="iOS" Value="OpenSans-Bold" />
    </OnPlatform>
    <OnPlatform x:TypeArguments="x:String" x:Key="NormalFont">
        <On Platform="Android" Value="OpenSans-Regular.ttf#Open Sans" />
        <On Platform="UWP" Value="/Assets/OpenSans-Regular.ttf#Open Sans" />
        <On Platform="iOS" Value="OpenSans-Regular" />
    </OnPlatform>
</ResourceDictionary>

要使用自定义字体,您只需:

<StackLayout>
    <Label Text="Welcome to Xamarin Forms! (OpenSans-Bold)" FontFamily="{StaticResource BoldFont}" />
    <Label Text="Welcome to Xamarin Forms! (OpenSans-Regular)" FontFamily="{StaticResource NormalFont}" />
    <Label Text="Welcome to Xamarin Forms! (Default)" />
</StackLayout>

答案 1 :(得分:0)

v4.5.530+ 中,您可以轻松添加自定义嵌入字体,而无需担心跨平台问题:

  • 在共享项目中添加自定义字体文件(*.tff*.otf)。

enter image description here

  • 右键单击字体文件 > 属性 > 在构建操作中选择嵌入资源

enter image description here

  • 在共享项目的某处添加 ExportFont 属性(通常在 App.xaml.csAssemblyInfo.cs 中)。
// "Font Awesome 5 Pro-Regular-400.otf" is the font file name witout the subfolders path
// Alias is the name to reference in code
[assembly: ExportFont("Font Awesome 5 Pro-Regular-400.otf", Alias = "FARegular")]

namespace YourProject.Shared
{
    public partial class App : Application
    {

        public App()
        {
            InitializeComponent();
            // ...
        }
    }
}
  • 更新控件中的自定义字体系列:
<Label FontFamily="FARegular" Text="&#xf002;" />

参考文献

相关问题