How do I use a custom font in a mobile app?
Choosing the correct font can uplift your interface and improve the user experience. LiveCode provides a useful set of functionality allowing us to handle fonts, which has recently been extended to cover the installation of custom fonts on mobile.
This lesson will detail how to use this functionality to install and use a custom font using a very simple font picker app.
Setting up the app
The app we're going to design will look like the one above, and will consist of
- a button to list what fonts are available
- a list field to show these fonts and allow you to select a font
- a field the selected font will be applied to
Once you have created and arranged these objects on the card, we need to apply a few lines of code to the button and our list field.
Our button is going to check what fonts are available on the machine our app is running on, and place them in our list field in alphabetical order. We can use the fontNames function to do this . This function returns a list of the fonts installed on the system. Our code should look something like this:
put the fontNames into tList
sort lines of tList
put tList into field "fontList"
Now we need to put code in our list field's script so that it can set the font of the text field to whatever font we select in the list field. Since each line in the list field is taken from the fontNames function, and as such is a valid font name, we can set the textFont of the field to the text of the selected line.
put line (the hilitedLine of me) of me into tFont
set the textFont of field "fontTest" to tFont
Including the custom font in the mobile app
If you run your app on a mobile device or simulator, you should now be able to see the list of default fonts available. This is likely to be shorter than if you run the app on a desktop computer.
To include a custom font in the mobile app we need to include it with the application bundle when we build our app as a standalone application. To do this include the font file in the Copy Files pane of the Standalone Application Settings.
When deploying to the mobile device Livecode will recognise the .ttf file extension for our font file, and install it as a custom font.
Using the newly installed custom font
After including this file in the list of files to be copied into the application bundle, if we build and run our app again we should see our custom font displayed in the list when we click 'List Fonts'. Clicking on it in the list, we can see our sample text change to the desired font.
Android and Font Names
There is a currently an issue where only the PostScript name of a font works on Android. Controls where the font has been set in the Property Inspector might need to have their font set to the PostScript name in code for the font to show as expected on Android.