2

I tried to change the 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;
}
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
loot verge
  • 449
  • 1
  • 12
  • 31

2 Answers2

6

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>
Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45
  • Thank you for your answer just one question. When I add my font to the Asset folder can I now use the font in my css file? – loot verge Oct 07 '18 at 16:37
2

In v4.5.530+, you can easily add custom embedded fonts without having to worry about cross platform issue:

  • Add your custom font file (*.tff, *.otf) in your shared project.

enter image description here

  • Right click the font file > Properties > in Build Action select Embedded Resource.

enter image description here

  • Add the ExportFont attribute somewhere in your shared project (usually inside App.xaml.cs or AssemblyInfo.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();
            // ...
        }
    }
}
  • Update the custom font family in your control:
<Label FontFamily="FARegular" Text="&#xf002;" />

References

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230