Androidを試す

昨日AndroidSDKが発表されたので早速試してみる。
http://code.google.com/android/index.html

まずAndroidとは何か。詳しい説明は「ん・ぱか工房」さんの「Androidメモ」が参考になる。
http://www.saturn.dti.ne.jp/~npaka/android/

SDKのインストール方法は。「cheprogramming」さんのところを参考にすると良いと思う。
http://chephes.cocolog-nifty.com/blog/2007/11/androidsdk_7866.html

新しい言語の基本"Hello, World"についてはオフィシャルHPのドキュメントにも有るし、
上記のブログでも解説されているのでここでは触れない。


そこで画像の読み込みについて扱おう。

Androidで画像を扱うにはプロジェクト内の./res/drwaable/に画像ファイルを入れなくてはならない。
ファイルを入れた後プロジェクトをビルドするとR.javaというファイルが生成され、画像のファイル名にIDが割り当てられているはずだ。
例えば"kirby.png"というファイルを入れてビルドした場合には、"R.java"内に、
public static final int kirby=0x7f020001;
という記述が増えているはずだ。
loadImageの第一引数であるfileidにはこのファイル名の部分(上の例だと"kirby")を入力する。その他の処理はソースを見ていただきたい。


なお画像は指定された大きさに合わせてリサイズされる。


以下は表示するのに使ったファイルと動作画面である。
http://gyazo.com/813edd8029d68d82eb2428b51a2ca4b2.png
http://gyazo.com/3102d3918ff3b929ca0c9427433994d7.png

package net.swelt.android.loadimage;

import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.content.Resources;
import android.graphics.*;
import android.view.View;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;

public class LoadImage extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(new SampleView(this));
    }
    
    private static class SampleView extends View {
    	private Paint mPaint = new Paint();
    	private Bitmap mBitmap;
    	
    	public SampleView(Context context) {
    		super(context);
    		mBitmap = loadImage(R.drawable.kirby, 128, 128);
    	}
    	
    	public Bitmap loadImage(int fileid, int width, int height) {
    		Resources r = this.getContext().getResources();
    		Bitmap bitmap = Bitmap.createBitmap(width, height, true);
    		Drawable drawable = r.getDrawable(fileid);
    		Canvas canvas = new Canvas(bitmap);
    		
    		drawable.setBounds(0, 0, width, height);
    		drawable.draw(canvas);
    		
    		return bitmap;
    	}
    	
    	@Override protected void onDraw(Canvas canvas) {
    		Paint paint = mPaint;
    		
    		canvas.drawColor(Color.WHITE);
    		
    		canvas.drawBitmap(mBitmap, 0, 0, paint);
    	}
    }
}