Android Game Framework Part 2
SurfaceView를 사용하여 User Thread에서 직접적으로 onDraw()를 호출할 수 있도록 설정한 예
GameActivity.java
package game.framework;
import android.app.Activity;
import android.os.Bundle;
public class GameActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
}
GameView.java
package game.framework;
import android.content.*;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.*;
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
GameViewThread gameThread;
public GameView(Context context) {
super(context);
getHolder().addCallback(this);
gameThread = new GameViewThread(getHolder(), this);
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(icon, 10, 10, null);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
gameThread.setRunning(true);
gameThread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameThread.setRunning(false);
while(retry){
try{
gameThread.join();
retry = false;
}catch(InterruptedException ie){
}
}
}
}
GameViewThread.java
package game.framework;
import android.graphics.*;
import android.view.*;
public class GameViewThread extends Thread {
private SurfaceHolder surfaceHolder;
private GameView gameView;
private boolean m_run;
public GameViewThread(SurfaceHolder surfaceHolder, GameView gameView) {
this.surfaceHolder = surfaceHolder;
this.gameView = gameView;
}
public void setRunning(boolean run) {
this.m_run = run;
}
@Override
public void run() {
Canvas canvas = null;
while(m_run) {
canvas = null;
try{
canvas = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
gameView.onDraw(canvas);
}
}catch(Exception ex){
}finally {
if(canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}