Sunday, February 17, 2013

Android beginner tutorial: Part 85 - Embedding fonts using Assets

In this tutorial we will learn how to load and use a font from an asset.

Assets are somewhat similar to resources, yet different. While resources are embedded into the application and can be referred to using the R class, assets are raw files that are stored in the assets directory and require us to manually read them to use them in our applications.

Today we'll learn how to embed and use a raw .ttf font file as an asset in our application.

First of all you need to find the ttf file. You can download fonts online, I use fontsquirrel.com - all the fonts there are free and pretty good.

Once you have the .ttf file, put it in the assets directory of your project.

Then go to activity_main.xml of your application and add a TextView there:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    
    <TextView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/myText"
        android:textSize="36sp"
        android:text="Hello world!"
        />
    
</LinearLayout>

Now go to MainActivity.java class and load the font using Typeface.createFromAsset() static method. Once the font is extracted, apply it to the text using setTypeface() method:

TextView mytext = (TextView)findViewById(R.id.myText);
Typeface face = Typeface.createFromAsset(getAssets(), "yukarimobil.ttf");
mytext.setTypeface(face);

Here's the full code:

package com.example.codeforfoodtest_two;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView mytext = (TextView)findViewById(R.id.myText);
Typeface face = Typeface.createFromAsset(getAssets(), "yukarimobil.ttf");
mytext.setTypeface(face);
}
}

It is that easy!

You can use assets to store all sorts of files and read them byte by byte or using what's provided by the Android SDK, like the Typeface.createFromAsset() method just now.

That's all for today.

Thanks for reading!

1 comment:

Post a Comment