リソースからBitmapを作成

広告

それではリソースとして配置した画像ファイルを利用して「Bitmap」クラスのオブジェクトを作成する方法を確認します。「BitmapFactory」クラスで用意されているstaticメソッドの「decodeResource」メソッドを使います。

Decode an image referenced by a resource ID.

Parameters:
  res  Resources
  id  resource ID
Returns:
  The resulting decoded bitmap, or null.

1番目の引数には引数には「Resources」クラスのオブジェクトを指定します。このオブジェクトはアプリケーションのリソースを管理しているものと考えて下さい。「android.content.Context」クラスで用意されている「getResources」メソッドを使って取得します。(「Activity」クラスは「Context」クラスのサブクラスです)。

public class Test extends Activity {

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

        Resources r = getResources();
    }
}

2番目の引数には対象の画像に割り当てられたリソースIDを指定します。

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

import android.app.Activity;
import android.os.Bundle;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.content.Resources;

public class Test extends Activity {

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

        Resources r = getResources();
        Bitmap bmp = BitmapFactory.decodeResource(r, R.drawable.star);
    }
}

サンプルプログラム

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

Test03_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.content.Resources;

public class Test03_01 extends Activity
{
    private final int FP = ViewGroup.LayoutParams.FILL_PARENT; 
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

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

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

        Resources r = getResources();
        Bitmap bmp1 = BitmapFactory.decodeResource(r, R.drawable.star);
        Bitmap bmp2 = BitmapFactory.decodeResource(r, R.drawable.star2);
        Bitmap bmp3 = BitmapFactory.decodeResource(r, R.drawable.star3);

        ImageView image1 = new ImageView(this);
        image1.setImageBitmap(bmp1);
        linearLayout.addView(image1, createParam(WC, WC));

        ImageView image2 = new ImageView(this);
        image2.setImageBitmap(bmp2);
        linearLayout.addView(image2, createParam(WC, WC));

        ImageView image3 = new ImageView(this);
        image3.setImageBitmap(bmp3);
        linearLayout.addView(image3, createParam(WC, WC));
    }

    private LinearLayout.LayoutParams createParam(int w, int h){
        return new LinearLayout.LayoutParams(w, h);
    }
}

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

リソースからBitmapを作成

各画像ファーマットで用意した画像が表示されました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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