Thursday, January 12, 2012

Simple Droid App that shows FPS and is a starter to Making a game

package simpleProjects.FPSTest;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class FPSTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        Panel pnl = new Panel(this);
        setContentView(pnl);     
       
    }
    
    class Panel extends View {

        
        // Processing handles fps pinning, but we
        // report fps on our own just to be sure.
        
        /** FPS that we want to achieve */
        final static float targetFPS = 60.0f;
        /** Number of frames to average over when computing real FPS */
        final int fpsAverageCount = 10; 
        /** Array of timings */
        long[] nanos;
        /** When we started the nanotimer */
        long nanoStart; //
        
        /** Number of frames since we started this example. */
        long frameCount = 0;          
        
        Paint _paint = new Paint();
        
        public Panel(Context context) {
            super(context);
        /* Set up the timers for FPS reporting */
        nanos = new long[fpsAverageCount];
        long nanosPerFrameGuess = (long)(1000000000.0 / targetFPS);
        nanos[fpsAverageCount-1] = System.nanoTime();
        for (int i=fpsAverageCount-2; i>=0; --i) {
        nanos[i] = nanos[i+1] - nanosPerFrameGuess;
        }
        nanoStart = System.nanoTime();
       
        _paint = new Paint();
    _paint.setTextSize(14F);
    _paint.setStyle(Paint.Style.FILL);
    _paint.setColor(0xFFDDDDDD);
   
   
    this.setFocusable(true);
    this.requestFocus();
        }
        
 
        @Override
        public void onDraw(Canvas canvas) {
        this.requestFocus();
            canvas.drawColor(Color.BLACK);
    for (int i=0; i<fpsAverageCount-1; ++i) {
    nanos[i] = nanos[i+1];
    }
    nanos[fpsAverageCount-1] = System.nanoTime();
    float averagedFPS = (float) ( (fpsAverageCount-1) * 1000000000.0 / (nanos[fpsAverageCount-1]-nanos[0]));
    ++frameCount;
    float totalFPS = (float) (frameCount * 1000000000 / (1.0*(System.nanoTime()-nanoStart)));
   
    canvas.drawText( "Average FPS ("+fpsAverageCount+" frames): "+averagedFPS, 10, 400, _paint);
    this.invalidate();            
        } //end onDraw
    }//end Panel class
    
}

No comments:

Post a Comment