Here we will see the steps to add custom fonts in Aamarin forms applications. Sometimes we have a requirement of showing our app with custom fonts or client selected fonts instead of the default fonts available in Xamarin forms.
If you want to add any custom font to your application, first we need to download our required font in to our system. If you unzip the downloaded font, you can find one '.ttf' file. For showing custom fonts, we need to add these '.ttf' files to each project.
Android
For Android projects, add '.ttf' file in 'Assets' folder and set build type is "AndroidAsset"
Ios
For iOS projects, Add '.ttf' file in 'Resource' folder and set build type is 'BundleResource'
Note
For iOS applications, we have to add file name of the fonts in 'info.plist' file additionally. Here is the sample code of adding font file names added in 'info.plist' file.
Sample code
- <key>UIAppFonts</key>
- <array>
- <string>font filename.ttf</string>
- </array>
After adding custom fonts '.ttf' files to projects, we have to create a resource object either in application level or page level for the custom fonts used in our application.
Sample code
- <ResourceDictionary>
- <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>
Where for IOS platform we need write the exact name of the file without extension, in Android platform we need to write filename with extension. In the above we write the font's actual name after hash (#). We can find the font's actual name, you will see it when you open the downloaded font folder. Here the font name will not be the same as the font file name every time.
Process of using custom fonts in xaml code:
By using staticresource dictionary we can consume custom fonts in xaml page.
Sample code
- <StackLayout>
- <Label Text="Welcome to Xamarin Forms! (OpenSans-Regular)" FontFamily="{StaticResource NormalFont}" />
- <Label Text="Welcome to Xamarin Forms! (Default)" />
- lt;/StackLayout>