) Android Tutorial: how to use a Custom font

Source: Internet
Author: User
Tags drawtext

It is quite troublesome to implement custom fonts on other platforms, but it is very easy on Android platforms.

First, place the Custom font under "assets" and instantiate it before use. The font file is shown in.

InProgramTo instantiate the Custom font as follows:

    1. Typeface. createfromasset (getcontext (). getassets (),"Fonts/samplefont. TTF");

The following figure shows the effects of the default font and Custom font of Android:

Source codeAs follows:

Package COM. yarin. android. typefaces; import android. app. activity; import android. content. context; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. graphics. typeface; import android. OS. bundle; import android. view. view; public class typefaces extends activity {/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (New sampleview (this);} Private Static class sampleview extends view {private paint mpaint = new paint (paint. anti_alias_flag); Private typeface mface; Public sampleview (context) {super (context); // instantiate the Custom font mface = typeface. createfromasset (getcontext (). getassets (), "fonts/samplefont. TTF "); // set the font size mpaint. settextsize (32) ;}@ override protected void ondraw (canvas) {canvas. drawcolor (color. white); // draw the default font mpaint. settypeface (null); canvas. drawtext ("Default: abcdefg", 10,100, mpaint); // draw a Custom font mpaint. settypeface (mface); canvas. drawtext ("custom: abcdefg", 10,200, mpaint );}}}

Now, we can implement custom fonts in this simple way.
Here are two very useful methods:

// Remove the Sawtooth paint. setflags (paint. anti_alias_flag) // obtain the string width paint. measuretext ()
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.