文字の水平方向への拡大率を設定

広告

文字を表示する際に、1つ1つの文字に対して水平方向の拡大率を設定する事ができます。例えば「2.0f」に設定すると1つの文字の横幅が2倍になって表示されます。拡大率を設定するには「TextView」クラスで用意されている「setTextScaleX」メソッドを使います。

Sets the extent by which text should be stretched horizontally.

Related XML Attributes:
  android:textScaleX

Parameters:
  size  拡大率(1.0fが通常サイズ)

1番目の引数に文字の拡大率をfloat型の値で指定します。1.0fを指定すると通常の大きさのままです。

具体的には次のように記述します。

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

public class Test extends Activity {
    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        TextView tv = new TextView(this);
        tv.setText("Text");
        tv.setTextScaleX(1.5f);
        setContentView(tv);
    }
}

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test06_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.widget.TextView;

public class Test06_01 extends Activity
{
    private final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT; 

    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);

        TextView tv1 = new TextView(this);
        tv1.setText("abcdef 0.5f");
        tv1.setTextScaleX(0.5f);
        linearLayout.addView(tv1, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv2 = new TextView(this);
        tv2.setText("abcdef 1.0f");
        tv2.setTextScaleX(1.0f);
        linearLayout.addView(tv2, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv3 = new TextView(this);
        tv3.setText("abcdef 1.5f");
        tv3.setTextScaleX(1.5f);
        linearLayout.addView(tv3, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        TextView tv4 = new TextView(this);
        tv4.setText("abcdef 2.0f");
        tv4.setTextScaleX(2.0f);
        linearLayout.addView(tv4, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}

ビルド後にエミュレーター上で実行します。

文字の水平方向への拡大率を設定

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。