marunomaruno-memo

marunomaruno-memo

[Android] フォント

2012年03月17日 | Android
[Android] フォント
================================================================================

■ 組込みのフォント

つぎの 4 つのフォントが組込みで使える。
    normal
    sans
    serif
    monospace

これらは、android:typeface 属性で出てくるものである。
ただし、日本語のフォントは変わらないみたい。

また、フォントのスタイルには、つぎの 3 つがある。
    normal
    bold
    italic


■ フォントの追加

また、使いたいフォントを、Android 実機に追加して使用することもできる。

フォントは True Type Font(ttf ファイル)を assets フォルダーの中に入れる。
今回は、assets フォルダーの中に fonts フォルダーを作り、ダウンロードしてきた 3 
つの ttf ファイルを入れて、それをボタンによってサイクリックに換えている。

フォントは
しねきゃぷしょん
http://chiphead.jp/font.htm
よりダウンロードしたものを使っている。

    字幕フォント           cinecaption227.ttf    
    ファミコン・フォント   FAMania2.6.ttf    
    トンパ文字             tompa1.50.ttf    


設定としては、ttf ファイルを assets フォルダーに入れたら、プログラムでは、以下の
ようにするだけ。

    Typeface tf = Typeface.createFromAsset(getAssets(), ttfファイルへのパス);
    ウィジェット.setTypeface(tf);


これらの指定は、ウィジェット全体に適用する。

---
★ 文章の中の一部だけを変更したいような場合は、HTML などを使う必要があるかもしれ
ない。
---

---
★ 実機の機種によって、追加したフォントが使えたり使えなかったりする。字幕みたい
なフォント cinecaption227.ttf が、IdeaPad A1 では使えて、Dell Streak では使えな
い。ただし、例外が出るわけではなく、対応する文字がないという感じ。なぜ?
なお、エミュレーターでも出なかった。
---


▲ アクティビティ

ダウンロードしてきたフォントを、ボタンがクリックされるたびにサイクリックに変更す
る。

□ TrueTypeFont01Activity.java
---
package jp.marunomaruno.android.truetypefont;

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

public class TrueTypeFont01Activity extends Activity {
    private int fontIndex = 0; // (1)
    private String[] names;
    private String[] descriptions;
    private Typeface[] typefaces;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        names = getResources().getStringArray(R.array.fontName); // (2)
        descriptions = getResources().getStringArray(R.array.fontDescription); // (3)

        String[] files = getResources().getStringArray(R.array.fontFile); // (4)
        typefaces = new Typeface[files.length];
        for (int i = 1; i < typefaces.length; i++) {
            typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
                    + files[i]); // (5)
        }
        typefaces[0] = Typeface.DEFAULT; // (6)
    }

    public void onClickNextFont(View view) throws Exception {
        try {
            fontIndex++; // (7)
            fontIndex %= names.length; // (8)

            TextView fontName = (TextView) findViewById(R.id.fontName);
            fontName.setText(names[fontIndex]);

            TextView fontText = (TextView) findViewById(R.id.fotTtext);
            fontText.setTypeface(typefaces[fontIndex]); // (9)
            fontText.setText(String.format("%s%n%s%n",
                    getString(R.string.hello), descriptions[fontIndex]));

        } catch (Exception e) { // (10)
            e.printStackTrace();
            throw e;
        }
    }
}
---

(1)(7)(8) サイクリックに変更するためのインデックス

インデックスの定義

    private int fontIndex = 0; // (1)

フォントが使われるたびにインクリメントして、フォントの数で割った余りをふたたび使
うようにする。

    fontIndex++; // (7)
    fontIndex %= names.length; // (8)


(2)(3)(4) フォント名、ファイル名、フォントを使った文章を取得

res/values/strings.xml に、string-array 要素として設定してある。

    names = getResources().getStringArray(R.array.fontName); // (2)
    descriptions = getResources().getStringArray(R.array.fontDescription); // (3)
    String[] files = getResources().getStringArray(R.array.fontFile); // (4)


(5) Typeface オブジェクトの生成

    typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
                + files[i]); // (5)


(6) デフォルト・フォントを設定

    typefaces[0] = Typeface.DEFAULT; // (6)


(9) Typeface オブジェクトの設定

    fontText.setTypeface(typefaces[fontIndex]); // (9)


(10) 例外の処理

フォントのファイル (ttf ファイル)がないときは、RuntimeException がスローされる。
メッセージはつぎのとおり。
    java.lang.RuntimeException: native typeface cannot be made

キャッチして、スタックトレースだけ出し、今回は、そのままスローしなおす。

    catch (Exception e) { // (10)



□ Typeface クラス

java.lang.Object
   +    android.graphics.Typeface

フォントを管理するクラス。

定数としては、フォントのタイプを表すものと、組込みのフォントが用意されている。

定数
---
int       BOLD    
int       BOLD_ITALIC    
int       ITALIC    
int       NORMAL    
Typeface  DEFAULT        
Typeface  DEFAULT_BOLD
Typeface  MONOSPACE    
Typeface  SANS_SERIF    
Typeface  SERIF        
---


ttf ファイルを指定して、フォントを生成する。

メソッド
---
static Typeface  create(String familyName, int style)
static Typeface  create(Typeface family, int style)
static Typeface  createFromAsset(AssetManager mgr, String path)
static Typeface  createFromFile(String path)
static Typeface  createFromFile(File path)
static Typeface  defaultFromStyle(int style)
int              getStyle()
final boolean    isBold()
final boolean    isItalic()
---


▲ レイアウト

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="normal アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="normal" />    <!-- (1) -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="sans アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="sans" />    <!-- (2) -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="serif アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="serif" />    <!-- (3) -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="monospace アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="monospace" />    <!-- (4) -->

    <TextView
        android:id="@+id/fontName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/defaultFont"
        android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (5) -->

    <Button
        android:id="@+id/nextFontButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClickNextFont"
        android:text="@string/nextFontButton"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/fotTtext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (6) -->

</LinearLayout>
---


(1)(2)(3)(4) 組込みフォントを表示

android:typeface 属性を使って、それぞれ、組込みフォントを表示している。
    normal
    sans
    serif
    monospace


(5) android:typeface 属性なし

デフォルトは normal かな。


(6) 追加フォントの文字を表示


上記サンプルでは使っていないが、太字などにする android:textStyle 属性もある。
以下の値が指定できる。
    normal
    bold
    italic

複数の値を指定したいときは、パイプ(|) を使って指定する。


▲ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, TrueTypeFont01Activity!</string>
    <string name="app_name">TrueTypeFont01</string>
    <string name="defaultFont">デフォルトのフォント</string>
    <string name="nextFontButton">次のフォント</string>

    <string-array name="fontName">
        <item>@string/defaultFont</item>
        <item>字幕フォント</item>
        <item>ファミコン・フォント</item>
        <item>トンパ文字</item>
    </string-array>
    <string-array name="fontFile">
        <item>-</item>
        <item>cinecaption227.ttf</item>
        <item>FAMania2.6.ttf</item>
        <item>tompa1.50.ttf</item>
    </string-array>
    <string-array name="fontDescription">
        <item>@string/defaultFont</item>
        <item>字幕みたいなフォント</item>
        <item>ファミコンもどきのフォント</item>
        <item>阿葵悪安伊亥一壱丑浦英猿岡億下加夏賀介角</item> 
                    <!-- トンパ文字に対応する文字が少ないため、適当な文字列 -->
    </string-array>

</resources>
--

なお、トンパ文字に対応する文字が少ないため、適当な文字列を記述している。
フォントの説明によると、現在は 150 文字を登録している、とのこと。

                                                                            以上


[Android] フォント

2012年03月17日 | Android

[Android] フォント
================================================================================

■ 組込みのフォント

つぎの 4 つのフォントが組込みで使える。
normal
sans
serif
monospace

これらは、android:typeface 属性で出てくるものである。
ただし、日本語のフォントは変わらないみたい。

また、フォントのスタイルには、つぎの 3 つがある。
normal
bold
italic


■ フォントの追加

また、使いたいフォントを、Android 実機に追加して使用することもできる。

フォントは True Type Font(ttf ファイル)を assets フォルダーの中に入れる。
今回は、assets フォルダーの中に fonts フォルダーを作り、ダウンロードしてきた 3
つの ttf ファイルを入れて、それをボタンによってサイクリックに換えている。

フォントは
しねきゃぷしょん
http://chiphead.jp/font.htm
よりダウンロードしたものを使っている。

字幕フォント cinecaption227.ttf
ファミコン・フォント FAMania2.6.ttf
トンパ文字 tompa1.50.ttf


設定としては、ttf ファイルを assets フォルダーに入れたら、プログラムでは、以下の
ようにするだけ。

Typeface tf = Typeface.createFromAsset(getAssets(), ttfファイルへのパス);
ウィジェット.setTypeface(tf);


これらの指定は、ウィジェット全体に適用する。

---
★ 文章の中の一部だけを変更したいような場合は、HTML などを使う必要があるかもしれ
ない。
---

---
★ 実機の機種によって、追加したフォントが使えたり使えなかったりする。字幕みたい
なフォント cinecaption227.ttf が、IdeaPad A1 では使えて、Dell Streak では使えな
い。ただし、例外が出るわけではなく、対応する文字がないという感じ。なぜ?
なお、エミュレーターでも出なかった。
---


▲ アクティビティ

ダウンロードしてきたフォントを、ボタンがクリックされるたびにサイクリックに変更す
る。

□ TrueTypeFont01Activity.java
---
package jp.marunomaruno.android.truetypefont;

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

public class TrueTypeFont01Activity extends Activity {
private int fontIndex = 0; // (1)
private String[] names;
private String[] descriptions;
private Typeface[] typefaces;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

names = getResources().getStringArray(R.array.fontName); // (2)
descriptions = getResources().getStringArray(R.array.fontDescription); // (3)

String[] files = getResources().getStringArray(R.array.fontFile); // (4)
typefaces = new Typeface[files.length];
for (int i = 1; i < typefaces.length; i++) {
typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
+ files[i]); // (5)
}
typefaces[0] = Typeface.DEFAULT; // (6)
}

public void onClickNextFont(View view) throws Exception {
try {
fontIndex++; // (7)
fontIndex %= names.length; // (8)

TextView fontName = (TextView) findViewById(R.id.fontName);
fontName.setText(names[fontIndex]);

TextView fontText = (TextView) findViewById(R.id.fotTtext);
fontText.setTypeface(typefaces[fontIndex]); // (9)
fontText.setText(String.format("%s%n%s%n",
getString(R.string.hello), descriptions[fontIndex]));

} catch (Exception e) { // (10)
e.printStackTrace();
throw e;
}
}
}
---

(1)(7)(8) サイクリックに変更するためのインデックス

インデックスの定義

private int fontIndex = 0; // (1)

フォントが使われるたびにインクリメントして、フォントの数で割った余りをふたたび使
うようにする。

fontIndex++; // (7)
fontIndex %= names.length; // (8)


(2)(3)(4) フォント名、ファイル名、フォントを使った文章を取得

res/values/strings.xml に、string-array 要素として設定してある。

names = getResources().getStringArray(R.array.fontName); // (2)
descriptions = getResources().getStringArray(R.array.fontDescription); // (3)
String[] files = getResources().getStringArray(R.array.fontFile); // (4)


(5) Typeface オブジェクトの生成

typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
+ files[i]); // (5)


(6) デフォルト・フォントを設定

typefaces[0] = Typeface.DEFAULT; // (6)


(9) Typeface オブジェクトの設定

fontText.setTypeface(typefaces[fontIndex]); // (9)


(10) 例外の処理

フォントのファイル (ttf ファイル)がないときは、RuntimeException がスローされる。
メッセージはつぎのとおり。
java.lang.RuntimeException: native typeface cannot be made

キャッチして、スタックトレースだけ出し、今回は、そのままスローしなおす。

catch (Exception e) { // (10)



□ Typeface クラス

java.lang.Object
+ android.graphics.Typeface

フォントを管理するクラス。

定数としては、フォントのタイプを表すものと、組込みのフォントが用意されている。

定数
---
int BOLD
int BOLD_ITALIC
int ITALIC
int NORMAL
Typeface DEFAULT
Typeface DEFAULT_BOLD
Typeface MONOSPACE
Typeface SANS_SERIF
Typeface SERIF
---


ttf ファイルを指定して、フォントを生成する。

メソッド
---
static Typeface create(String familyName, int style)
static Typeface create(Typeface family, int style)
static Typeface createFromAsset(AssetManager mgr, String path)
static Typeface createFromFile(String path)
static Typeface createFromFile(File path)
static Typeface defaultFromStyle(int style)
int getStyle()
final boolean isBold()
final boolean isItalic()
---


▲ レイアウト

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="normal アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="normal" /> <!-- (1) -->

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="sans アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="sans" /> <!-- (2) -->

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="serif アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="serif" /> <!-- (3) -->

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="monospace アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="monospace" /> <!-- (4) -->

<TextView
android:id="@+id/fontName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/defaultFont"
android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (5) -->

<Button
android:id="@+id/nextFontButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickNextFont"
android:text="@string/nextFontButton"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/fotTtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (6) -->

</LinearLayout>
---


(1)(2)(3)(4) 組込みフォントを表示

android:typeface 属性を使って、それぞれ、組込みフォントを表示している。
normal
sans
serif
monospace


(5) android:typeface 属性なし

デフォルトは normal かな。


(6) 追加フォントの文字を表示


上記サンプルでは使っていないが、太字などにする android:textStyle 属性もある。
以下の値が指定できる。
normal
bold
italic

複数の値を指定したいときは、パイプ(|) を使って指定する。


▲ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="hello">Hello World, TrueTypeFont01Activity!</string>
<string name="app_name">TrueTypeFont01</string>
<string name="defaultFont">デフォルトのフォント</string>
<string name="nextFontButton">次のフォント</string>

<string-array name="fontName">
<item>@string/defaultFont</item>
<item>字幕フォント</item>
<item>ファミコン・フォント</item>
<item>トンパ文字</item>
</string-array>
<string-array name="fontFile">
<item>-</item>
<item>cinecaption227.ttf</item>
<item>FAMania2.6.ttf</item>
<item>tompa1.50.ttf</item>
</string-array>
<string-array name="fontDescription">
<item>@string/defaultFont</item>
<item>字幕みたいなフォント</item>
<item>ファミコンもどきのフォント</item>
<item>阿葵悪安伊亥一壱丑浦英猿岡億下加夏賀介角</item>
<!-- トンパ文字に対応する文字が少ないため、適当な文字列 -->
</string-array>

</resources>
--

なお、トンパ文字に対応する文字が少ないため、適当な文字列を記述している。
フォントの説明によると、現在は 150 文字を登録している、とのこと。

以上