在 iOS 编程中,我们可以使用 CADisplayLink 以便在每次屏幕刷新时调用我们的处理程序。这个想法是推进游戏/动画状态,然后将其绘制到屏幕上。要获取当前时间,我们可以使用事件处理程序中的 displayLink.timestamp。但是,为什么当我在设备上运行它时,它返回的值与之前对处理程序的调用相同?因此,我无法正确计算经过的时间,因为它将为 0。
使用 NSDate 找到时间是可行的。在模拟器上运行有效。
这是相关的代码。假设您从 XCode 创建单个视图应用程序。然后修改视图控制器的头文件如下:
@interface MBIViewController : UIViewController
{
float _lastTimeStamp;
NSDate *_lastDate;
}
-(void)updateView:(CADisplayLink *)displayLink; // using displayLink.timestamp
-(void)updateView2:(CADisplayLink *)displayLink; // using NSDate
@end
然后在 viewDidLoad 中挂钩处理程序:
_lastTimeStamp = CACurrentMediaTime();
_lastDate = [NSDate date];
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateView:)]; // change this to updateView2: to compare
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
然后是2个处理程序:
-(void)updateView:(CADisplayLink *)displayLink
{
float newTimeStamp = displayLink.timestamp;
float elapsedTime = newTimeStamp - _lastTimeStamp;
float fps = 1.0f / elapsedTime;
_lastTimeStamp = newTimeStamp;
NSLog(@"elapsed time: %f", elapsedTime);
NSLog(@"fps: %f", fps);
NSLog(@"---");
}
-(void)updateView2:(CADisplayLink *)displayLink
{
NSDate *newDate = [NSDate date];
float elapsedTime = [newDate timeIntervalSinceDate:_lastDate];
float fps = 1.0f / elapsedTime;
_lastDate = newDate;
NSLog(@"elapsed time: %f", elapsedTime);
NSLog(@"fps: %f", fps);
NSLog(@"---");
}
这是设备上 updateView: 的输出:
2013-07-06 19:07:06.274 DisplayLinkTest[24842:907] elapsed time: 0.000000
2013-07-06 19:07:06.281 DisplayLinkTest[24842:907] fps: inf
2013-07-06 19:07:06.286 DisplayLinkTest[24842:907] ---
2013-07-06 19:07:06.291 DisplayLinkTest[24842:907] elapsed time: 0.000000
2013-07-06 19:07:06.298 DisplayLinkTest[24842:907] fps: inf
2013-07-06 19:07:06.303 DisplayLinkTest[24842:907] ---
2013-07-06 19:07:06.308 DisplayLinkTest[24842:907] elapsed time: 0.000000
2013-07-06 19:07:06.315 DisplayLinkTest[24842:907] fps: inf
2013-07-06 19:07:06.321 DisplayLinkTest[24842:907] ---
2013-07-06 19:07:06.325 DisplayLinkTest[24842:907] elapsed time: 0.062500
2013-07-06 19:07:06.329 DisplayLinkTest[24842:907] fps: 16.000000
2013-07-06 19:07:06.333 DisplayLinkTest[24842:907] ---
正确时,始终为 16fps。
如果您连接到 updateView2: 会发生以下情况:
2013-07-06 19:16:03.318 DisplayLinkTest[24871:907] elapsed time: 0.016677
2013-07-06 19:16:03.322 DisplayLinkTest[24871:907] fps: 59.962959
2013-07-06 19:16:03.325 DisplayLinkTest[24871:907] ---
2013-07-06 19:16:03.335 DisplayLinkTest[24871:907] elapsed time: 0.016731
2013-07-06 19:16:03.339 DisplayLinkTest[24871:907] fps: 59.769207
2013-07-06 19:16:03.342 DisplayLinkTest[24871:907] ---
2013-07-06 19:16:03.352 DisplayLinkTest[24871:907] elapsed time: 0.017200
2013-07-06 19:16:03.357 DisplayLinkTest[24871:907] fps: 58.139557
2013-07-06 19:16:03.365 DisplayLinkTest[24871:907] ---
2013-07-06 19:16:03.369 DisplayLinkTest[24871:907] elapsed time: 0.017283
2013-07-06 19:16:03.374 DisplayLinkTest[24871:907] fps: 57.860249
我是否错误地使用了 displayLink.timestamp?谢谢