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

loo*_*rge 2 c# xamarin.android xamarin xamarin.forms

我尝试使用 CSS 和 XAML 更改标签的字体系列,但字体没有反映。我正在尝试在我的应用程序中使用 Montserrat 字体。我怎样才能解决这个问题?

XAML 代码:

<Label StyleClass="label" Text="Sample"/>
Run Code Online (Sandbox Code Playgroud)

CSS代码:

.label{
    font-family: Montserrat;
}
Run Code Online (Sandbox Code Playgroud)

Bru*_*iro 5

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

在您的 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>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)