|
很多朋友在开发的时候都需要用到帧率计算,我封装了一个类用起来还算是方便共享给大家玩玩。经过测试,在模拟器上25帧的,真机大该都能达到50左右。
package com.chuguangming;
import android.app.Activity;
import android.os.Bundle;
public class FPS extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new FpsSurfaceView(this));
}
}
复制代码
复制代码package com.chuguangming;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class FpsSurfaceView extends SurfaceView implements Callback
{
String fps = ""; // 用于显示帧速率的字符串,调试使用
FpsThread fpsThread;
public FpsSurfaceView(Context context)
{
super(context);
getHolder().addCallback(this);
fpsThread=new FpsThread(getHolder());
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
if (!fpsThread.isAlive())
{ // 如果DrawThread没有启动,就启动这个线程
fpsThread.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
}
复制代码
复制代码package com.chuguangming;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class FpsThread extends Thread
{
SurfaceHolder fpsHolder;
boolean flag = false; // 线程执行标志位
int sleepSpan = 30; // 休眠时间
long start = System.nanoTime(); // 记录起始时间,该变量用于计算帧速率
int count = 0; // 记录帧数,该变量用于计算帧速率
private String SurfaceViewfps;
public FpsThread( SurfaceHolder holder)
{
fpsHolder = holder;
flag = true;
}
@Override
public void run()
{
Canvas canvas = null;
while (flag)
{
try
{
canvas = fpsHolder.lockCanvas(null);
synchronized (fpsHolder)
{
canvas.drawColor(Color.RED);
Paint p = new Paint(); // 创建画笔对象
p.setColor(Color.BLUE); // 为画笔设置颜色
p.setTextSize(18); // 为画笔设置字体大小
p.setAntiAlias(true); // 设置抗锯齿
canvas.drawText(SurfaceViewfps, 30, 30, p); // 画出帧速率字符串
}
} catch (Exception ex)
{
ex.printStackTrace();
} finally
{
if (canvas != null)
{ // 如果canvas不为空
fpsHolder.unlockCanvasAndPost(canvas);// surfaceHolder解锁并将画布对象传回
}
}
this.count++;
if (count == 20)
{ // 如果计满20帧
count = 0; // 清空计数器
long tempStamp = System.nanoTime();// 获取当前时间
long span = tempStamp - start; // 获取时间间隔
start = tempStamp; // 为start重新赋值
// 四舍五入
// 先得到100秒能包含几个span,再乘于20就得到了100S能绘制几帧
// 再除于100就得到了一秒为几个帧了
double fps = Math.round(100000000000.0 / span * 20) / 100.0;// 计算帧速率
SurfaceViewfps= "FPS:" + fps;
}
try
{
Thread.sleep(sleepSpan); // 线程休眠一段时间
} catch (Exception e)
{
e.printStackTrace(); // 捕获并打印异常
}
}
super.run();
}
}
复制代码
完整代码:
登录才可以下载或查看附件。没有帐号?免费加入 |
|