2012年2月16日木曜日

SurfaceViewを使ったアニメーション


package com.sample.surface.test;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SurfaceViewTest01Activity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

AnimationSurfaceView surfaceView;
surfaceView = new AnimationSurfaceView(this);
setContentView(surfaceView);

}


/**
*
* SurfaceViewクラス
* アニメーションを実行する。
*/
public class AnimationSurfaceView extends SurfaceView
implements Runnable, SurfaceHolder.Callback {

static final int SIZE_X = 30;
static final int SIZE_Y = 30;

int positionX = 0;
int positionY = 0;

int screenWidth;
int screenHeight;

SurfaceHolder surfaceHolder;
Thread thread;

public AnimationSurfaceView(Context context) {
super(context);
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
}

@Override
public void run() {

Canvas canvas = null;
Paint paintBlue  = new Paint();
Paint paintWhite = new Paint();

paintWhite.setStyle(Style.FILL);
paintWhite.setColor(Color.WHITE);

paintBlue.setStyle(Style.FILL);
paintBlue.setColor(Color.BLUE);


while(thread != null){

try{
canvas = surfaceHolder.lockCanvas();

canvas.drawRect(//背景
0,
0,
screenWidth, screenHeight,
paintWhite);

canvas.drawRect(//平行移動する四角形
positionX,
positionY,
positionX + SIZE_X,
positionY + SIZE_Y,
paintBlue);

positionX += 1;//x移動
positionY += 1;//y移動

surfaceHolder.unlockCanvasAndPost(canvas);

}
catch(Exception e){}
}
}

@Override
public void surfaceChanged(
SurfaceHolder holder,
int format,
int width,
int height) {
screenWidth = width;
screenHeight = height;
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
thread = new Thread(this);
thread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
thread = null;
}
}
}

0 件のコメント:

コメントを投稿