Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidで画像にテキストを描画する方法|初心者向けサンプルコード解説

はじめに

この記事では、Androidアプリで画像の上にテキストを描画(表示)する方法を、サンプルコードを交えながらステップごとに解説します。

もっとも簡単なのは、ImageViewTextViewRelativeLayout上で重ねて配置する方法です。写真にキャプションを付けるような演出を、わずかなコードで実現できます。


手順1:新規プロジェクトを作成する

Android Studioを起動し、メニューから[File] → [New Project]を選択して新しいプロジェクトを作成します。必要事項を入力してセットアップを完了させましょう。

手順2:レイアウトファイルを編集する

あらかじめ表示したい画像ファイル(例:image.jpg)をres/drawableフォルダにコピーしておきます。そのうえで、res/layout/activity_main.xmlに以下のコードを記述します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:background="@drawable/image"/>
    <TextView
        android:id="@+id/text"
        android:textStyle="bold|italic"
        android:textSize="24sp"
        android:padding="4dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="16sp"/>
</RelativeLayout>

ポイント: TextViewにandroid:layout_alignParentBottom="true"を指定することで、画面の下部に配置され、背後にある画像の上に重なって表示されます。

手順3:MainActivity.java を編集する

src/MainActivity.javaに以下のコードを記述します。

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        textView.setText("This is the place where i want to live");
        textView.setTextColor(Color.WHITE);
    }
}

setText()で表示する文字列を設定し、setTextColor(Color.WHITE)でテキスト色を白に指定しています。日本語の文字列もそのまま設定できます。

手順4:AndroidManifest.xml を確認する

AndroidManifest.xmlは以下のようになります。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行する

それではアプリを実行してみましょう。実機のAndroidデバイスをパソコンに接続していることを確認してください。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの実行(Run)アイコンをクリックします。接続したデバイスを選択すると、端末の画面に次のように画像の上へテキストが表示されます。

Androidで画像にテキストを描画する方法|初心者向けサンプルコード解説

補足:Canvasを使って画像そのものにテキストを描画する

レイアウトで重ねる方法のほかに、CanvasクラスとPaintクラスを使ってBitmapオブジェクトに直接テキストを描き込む方法もあります。この手法なら、テキストが焼き込まれた画像をそのままファイルに保存することも可能です。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(60f);
canvas.drawText("Hello, Android!", 40, 120, paint);
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);

まとめ

Androidで画像にテキストを表示する場合、ImageViewとTextViewを重ねる方法が最も手軽です。一方、加工済みの画像として保存や共有を行いたいケースでは、Canvasによる描画が有効です。用途に合わせて上手く使い分けてみてください。

  1. 【Android】TextViewでテキストを両端揃え(ジャスティファイ)表示する方法

    概要 本記事では、AndroidアプリのTextViewに表示するテキストを両端揃え(ジャスティファイ)にする方法を、サンプルコードとともにわかりやすく解説します。 TextViewで両端揃えを実現するには、android:justificationMode=inter_wordを指定するだけです。この機能はAndroid 8.0(APIレベル26)以降で有効になるため、それ以前のOSバージョンでは無視される点に注意してください。 手順1:新規プロジェクトを作成する まず、Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。必要な項目をす

  2. 【Android】TextViewでテキストを両端揃え(ジャスティファイ)表示する方法を徹底解説

    この記事では、AndroidアプリのTextViewでテキストを両端揃え(ジャスティファイ)表示する方法を、実際のサンプルコードをもとに段階的に解説します。RecyclerViewを使ったリスト表示の実装例もあわせて紹介するので、Androidアプリ開発の基礎固めとしても役立つ内容です。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから「File」→「New Project」を選択します。必要な設定項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:res/layout/activity_main.xml