Using Default Fonts and Typefaces Android

Android provides several default font typefaces and styles. Applications can also use custom fonts by including font files as application assets and loading them using the AssetManager,much as one would use resources.

Using Default Fonts and Typefaces

By default,Android uses the Sans Serif typeface, but Monospace and Serif typefaces are also available. The following code excerpt draws some antialiased text in the default typeface (Sans Serif) to a Canvas:

You can instead load a different typeface, such as Monotype:

Perhaps you would prefer italic text, in which case you can simply set the style of the typeface and the font family:

You can set certain properties of a typeface such as antialiasing, underlining, and strikethrough using the setFlags() method of the Paint object:

Figure shows some of the Typeface families and styles available by default on Android.

Some typefaces and typeface styles available on Android.

Some typefaces and typeface styles available on Android

Using Custom Typefaces

You can easily use custom typefaces with your application by including the font file as an application asset and loading it on demand. Fonts might be used for a custom look-and feel, for implementing language symbols that are not supported natively, or for custom symbols.

For example, you might want to use a handy chess font to implement a simple, scalable chess game. A chess font includes every symbol needed to implement a chessboard, including the board and the pieces. Hans Bodlaender has kindly provided a free chess font called Chess Utrecht. Using the Chess Utrecht font, the letter Q draws a black queen on a white square, whereas a q draws a white queen on a white square, and so on.

To use a custom font, such as Chess Utrecht, simply download the font from the website and copy the chess1.ttf file from your hard drive to the project directory /assets/fonts/chess1.ttf. Now you can load the Typeface object programmatically much as you would any resource:

You can then use the Chess Utrecht typeface to “draw” a chessboard using the appropriate character sequences.

Using the Chess Utrecht font to draw a chessboard

Using the Chess Utrecht font to draw a chessboard

Measuring Text Screen Requirements

You can measure how large text with a given Paint is and how big of a rectangle you need to encompass it using the measureText() and getTextBounds() methods.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Android Topics