


class GameSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private GameMgr _gameMgr = new GameMgr();
private Thread _thread;
public GameSurfaceView(Context context) {
super(context);
getHolder().addCallback(this);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//解像度情報変更通知
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
_thread = new Thread(this); //別スレッドでメインループを作る
_thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
_thread = null;
}
@Override
public void run() {
while (_thread!=null) { //メインループ
_gameMgr.onUpdate();
onDraw(getHolder());
}
}
private void onDraw(SurfaceHolder holder) {
Canvas c = holder.lockCanvas();
if(c == null){
return;
}
_gameMgr.onDraw(c);
holder.unlockCanvasAndPost(c);
}
}
public abstract class Task {
public boolean onUpdate(){
return true;
}
public void onDraw(Canvas c){
}
}
public class FpsController extends Task {
private long _startTime = 0; //測定開始時刻
private int _cnt = 0; //カウンタ
private Paint _paint = new Paint(); //paint情報
private float _fps; //fps
private final static int N = 60; //平均を取るサンプル数
private final static int FONT_SIZE = 20;//フォントサイズ
public FpsController(){
_paint.setColor(Color.BLUE); //フォントの色を青に設定
_paint.setTextSize(FONT_SIZE); //フォントサイズを設定
}
@Override
public boolean onUpdate(){
if( _cnt == 0 ){ //1フレーム目なら時刻を記憶
_startTime = System.currentTimeMillis();
}
if( _cnt == N ){ //60フレーム目なら平均を計算する
long t = System.currentTimeMillis();
_fps = 1000.f/((t-_startTime)/(float)N);
_cnt = 0;
_startTime = t;
}
_cnt++;
return true;
}
@Override
public void onDraw(Canvas c){
c.drawText(String.format("%.1f", _fps), 0, FONT_SIZE-2, _paint);
}
}
public class GameMgr {
private LinkedList<Task> _taskList = new LinkedList<Task>(); //タスクリスト
GameMgr(){
_taskList.add( new FpsController() );
}
public boolean onUpdate() {
for(int i=0; i<_taskList.size(); i++){
if(_taskList.get(i).onUpdate() == false){ //更新失敗なら
_taskList.remove(i); //そのタスクを消す
i--;
}
}
return true;
}
public void onDraw(Canvas c) {
c.drawColor(Color.WHITE); //白で塗りつぶす
for(int i=0; i<_taskList.size(); i++){
_taskList.get(i).onDraw(c);//描画
}
}
}

Portions of this page are modifications
based on work created and shared by Google and used according to terms
described in the Creative Commons 3.0 Attribution License.
- Remical Soft -