▼Androidメモ▼
サーフェイスビュー


画像が画面内をバウンドしながら移動するプログラムを作成する。



リソース
画像「samplegif」をNavigationbarのツリーの「res/drawable」に挿入。

sample.gif


ソースコード
SurfaceViewEx.java
package net.npaka.surfaceviewex;
import android.app.*;
import android.os.*;
import android.graphics.*;
import android.view.*;

//サーフェイスビューの利用
public class SurfaceViewEx extends Activity {
    //初期化
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(new SurfaceViewView(this));
    }
}


SurfaceViewView.java
package net.npaka.surfaceviewex;
import android.content.res.*;
import android.content.*;
import android.graphics.*;
import android.view.*;

//サーフェイスビューの利用
public class SurfaceViewView extends SurfaceView 
    implements SurfaceHolder.Callback,Runnable {
    private SurfaceHolder holder;//サーフェイスホルダー
    private Thread        thread;//スレッド

    private Bitmap image;//イメージ
    private int    px=0; //X座標
    private int    py=0; //Y座標
    private int    vx=10;//X速度
    private int    vy=10;//Y速度
    
    //コンストラクタ
    public SurfaceViewView(Context context) {
        super(context);

        //画像の読み込み
        Resources r=getResources();
        image=BitmapFactory.decodeResource(r,R.drawable.sample);  
                
        //サーフェイスホルダーの生成
        holder=getHolder();
        holder.addCallback(this);
        holder.setFixedSize(getWidth(),getHeight());
    }

    //サーフェイスの生成
    public void surfaceCreated(SurfaceHolder holder) {
        thread=new Thread(this);
        thread.start();
    }

    //サーフェイスの終了
    public void surfaceDestroyed(SurfaceHolder holder) {
        thread=null;
    }

    //サーフェイスの変更
    public void surfaceChanged(SurfaceHolder holder,
        int format,int w,int h) {
    }   
      
    //スレッドの処理
    public void run() {                      
        Canvas canvas;
        while(thread!=null) {
            //ロック
            canvas=holder.lockCanvas();

            //描画
            canvas.drawColor(Color.WHITE);
            canvas.drawBitmap(image,px-57,py-57,null);

            //アンロック
            holder.unlockCanvasAndPost(canvas);
                
            //移動
            if (px<0 || getWidth()<px) vx=-vx;
            if (py<0 || getHeight()<py) vy=-vy;
            px+=vx;
            py+=vy;
                
            //スリープ
            try {
                Thread.sleep(50);
            } catch (Exception e) {
            }
        }
    }
}



−戻る−