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

【Android開発】Bitmap(ビットマップ)をDrawableに変換する方法をサンプルコード付きで解説

この記事では、Androidアプリ開発においてBitmap(ビットマップ)をDrawableに変換する方法を、実際のサンプルコードとともにステップ形式で解説します。画像の描画やカスタムビューの実装などで頻繁に必要となる処理なので、ぜひ参考にしてください。

全体の流れ

本チュートリアルでは、ボタンをタップするとリソースから取得したDrawableをBitmapに変換し、さらにそのBitmapを新しいDrawableとしてImageViewに表示するというシンプルなアプリを作成します。

ステップ1:新規プロジェクトの作成

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。

ステップ2:レイアウトファイル(activity_main.xml)の編集

次に、res/layout/activity_main.xmlに以下のコードを追加します。ここでは、変換を実行するためのButtonと、結果を表示するためのImageViewを配置しています。

<?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"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btnConvert"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert bitmap to Drawable" />
    <ImageView
        android:id="@+id/imageView"
        android:layout_below="@id/btnConvert"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

ステップ3:MainActivity.javaの実装

続いて、src/MainActivity.javaに以下のコードを記述します。ポイントは以下の3つです。

  • getResources().getDrawable()でリソースからDrawableを取得する
  • ((BitmapDrawable) drawable).getBitmap()でDrawableからBitmapを取り出す
  • new BitmapDrawable(bitmap)でBitmapから新しいDrawableを生成し、ImageViewにセットする
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    Button button;
    Bitmap bitmap;
    Drawable drawable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
        button = findViewById(R.id.btnConvert);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawable = getApplicationContext().getResources().getDrawable(R.drawable.image);
                bitmap = ((BitmapDrawable)drawable).getBitmap();
                Drawable d = new BitmapDrawable(bitmap);
                imageView.setImageDrawable(d);
            }
        });
    }
}

なお、R.drawable.imageの部分には、あらかじめres/drawableフォルダに配置した画像リソース名を指定してください。

ステップ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(実行)アイコンをクリックします。表示された選択肢から接続中のモバイルデバイスを選択すると、実機の画面にアプリが起動します。

ボタンをタップすると、指定した画像リソースがBitmap経由でDrawableに変換され、ImageViewに表示されることが確認できます。

  1. 【Android】Drawableの色を変更する方法を初心者向けに解説

    はじめにこの記事では、AndroidアプリでDrawable(ドローアブル)の色を変更する方法を、実際のコード例を交えながらステップごとに解説します。サンプルでは AnimationDrawable を活用し、背景のグラデーションが滑らかにフェードしながら切り替わるアニメーションを実装します。ステップ1:新規プロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。ステップ2:レイアウトファイル(activity_main.xml)を編集するres/layout

  2. AndroidでスクリーンショットをPDFに変換する3つの簡単な方法

    重要な情報のスクリーンショットを撮るのはとても便利ですが、保存先としてPDFファイルが用意されていない場合もあります。PDFは、画像など他のファイル形式と違い、共有先によって形式が変化することなく、元の情報の形を保ったまま保存できるため、重要情報の保管に広く使われています。また、将来的に印刷する可能性がある情報も、PDF形式で保存しておくのがおすすめです。この記事では、Androidでスクリーンショットを簡単にPDFへ変換できる3つの方法をご紹介します。方法1:Googleフォトアプリを使うGoogleフォトは、ほぼすべてのAndroidスマートフォンにプリインストールされている画像管理アプリ