欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS - CADisplayLink

程序员文章站 2022-03-09 19:48:50
...

CADisplayLink

和NSTimer一样,起一个定时作用,但是定时时间是固定的每一帧 1/60s。这个定时适合做动画

 //新建,添加
  let ca =  CADisplayLink(target: self, selector: Selector("doAction"))
  ca.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
  //移除,无效化
  ca.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
  ca.invalidate()
  ##//执行doAction每秒60次

应用

1.性能监视器,界面渲染一般60贞/秒为流畅,中心思想
属性:duration 官方翻译如下:
The value for duration is undefined before the target’s selector has been called at least once. Your application can calculate the amount of time it has to render each frame by multiplying duration
by frameInterval
总之一句话就是相邻2次执行时间的间隔,当间隔时间加起来达到1秒的时候,看起被调用多少次

import Foundation
import UIKit
class SunFPSLabel: UILabel {
    var ca: CADisplayLink!
    var count                           = 0
    let rM                              = NSRunLoop.mainRunLoop()
    var lastTime:CFTimeInterval         = 0
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setup()
    }
    func setup(){
        self.textColor = UIColor.blackColor()
        ca = CADisplayLink(target: self, selector: #selector(SunFPSLabel.heart(_:)))
        ca.addToRunLoop(rM, forMode: NSRunLoopCommonModes)
    }
    deinit{
        ca.invalidate()
        ca.removeFromRunLoop(rM, forMode: NSRunLoopCommonModes)
    }
    func heart(calink: CADisplayLink){
        guard (lastTime != 0) else {
            lastTime = calink.timestamp
            return
        }
        count      += 1
        let  offsetTime = calink.timestamp - lastTime;
        guard offsetTime > 1 else{
            return
        }
        let fps     = Double(count) / offsetTime
        lastTime    = calink.timestamp
        count       = 0
        let attr                =  NSMutableAttributedString(string: "\(Int(round(fps))) FPS")
        self.attributedText     =  attr
    }
}