表示するBitmapの指定

広告

ImageViewに表示する画像を指定する方法を確認します。「ImageView」クラスで用意されている「setImageBitmap」メソッドを使います。


Parameters:
  bm  表示するBitmap

1番目の引数に表示するBitmapクラスのオブジェクトを指定します。(Bitmapクラスについては「Bitmapクラス」を参照して下さい)。

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

private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

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

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

    ImageView image = new ImageView(this);
    image.setImageBitmap(bmp);
    setContentView(image, new LayoutParams(WC, WC));
}

サンプルプログラム

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

Test02_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 Test02_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.star1);
        Bitmap bmp2 = BitmapFactory.decodeResource(r, R.drawable.star2);

        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(bmp1);
        linearLayout.addView(image3, createParam(100, 100));
    }

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

また画像をリソースとしてプロジェクト内の「res/drawable」ディレクトリに配置しました。

表示するBitmapの指定

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

表示するBitmapの指定

画像リソースからBitmapクラスのオブジェクトを作成し、Bitmapクラスのオブジェクトを使ってImageViewクラスのオブジェクトを作成しています。

3番目に表示されているImageViewクラスのオブジェクトはサイズを指定しているため本来の画像のサイズから拡大・縮小されて表示されています。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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