JCFPSLabel.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // JCFPSLabel.swift
  3. // JChat
  4. //
  5. // Created by deng on 2017/3/8.
  6. // Copyright © 2017年 HXHG. All rights reserved.
  7. //
  8. // Reference: ibireme/YYKit/YYFPSLabel
  9. //
  10. import UIKit
  11. class JCFPSLabel: UILabel {
  12. public override init(frame: CGRect) {
  13. super.init(frame: frame)
  14. build()
  15. }
  16. public required init?(coder aDecoder: NSCoder) {
  17. super.init(coder: aDecoder)
  18. build()
  19. }
  20. public override var intrinsicContentSize: CGSize {
  21. return CGSize(width: 55, height: 20)
  22. }
  23. public override func willMove(toWindow newWindow: UIWindow?) {
  24. super.willMove(toWindow: newWindow)
  25. if newWindow == nil {
  26. _link.invalidate()
  27. } else {
  28. _link.add(to: RunLoop.main, forMode: RunLoop.Mode.common)
  29. }
  30. }
  31. @inline(__always) private func build() {
  32. text = "calc..."
  33. font = UIFont.systemFont(ofSize: 14)
  34. textColor = UIColor.white
  35. textAlignment = .center
  36. backgroundColor = UIColor(white: 0, alpha: 0.7)
  37. layer.cornerRadius = 5
  38. layer.masksToBounds = true
  39. }
  40. private dynamic func tack(_ link: CADisplayLink) {
  41. guard let lastTime = _lastTime else {
  42. _lastTime = link.timestamp
  43. return
  44. }
  45. _count += 1
  46. let delta = link.timestamp - lastTime
  47. guard delta >= 1 else {
  48. return
  49. }
  50. let fps = Double(_count) / delta + 0.03
  51. let progress = CGFloat(fps / 60)
  52. let color = UIColor(hue: 0.27 * (progress - 0.2), saturation: 1, brightness: 0.9, alpha: 1)
  53. let text = NSMutableAttributedString(string: "\(Int(fps)) FPS")
  54. text.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSMakeRange(0, text.length - 3))
  55. attributedText = text
  56. _count = 0
  57. _lastTime = link.timestamp
  58. }
  59. private var _count: Int = 0
  60. private var _lastTime: TimeInterval?
  61. private lazy var _link: CADisplayLink = {
  62. return CADisplayLink(target: self, selector: #selector(type(of: self).tack(_:)))
  63. }()
  64. }