How to change font family of label in Xamarin.Forms

被刻印的时光 ゝ 提交于 2021-01-29 07:12:44

问题


I tried to change font-family of my label using CSS and XAML but the font is not reflecting. I am trying to use Montserrat font in my app. How can I fix this?

XAML Code:

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

CSS code:

.label{
    font-family: Montserrat;
}

回答1:


In order to use custom fonts in your project, you have to do the following:

In your Android Project, place your font file in your Assets folder, and ensure the build type is AndroidAsset.

Then you can, in your XAML, declare the font in the resource dictionary (For example in 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>

To use the custom font, you can simply:

<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>


来源:https://stackoverflow.com/questions/52689641/how-to-change-font-family-of-label-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!