MKRingProgressLayer.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2015 Max Konovalov
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. import UIKit
  21. @objc(MKRingProgressLayer)
  22. open class RingProgressLayer: CALayer {
  23. /// The progress ring start color.
  24. @objc open var startColor: CGColor = UIColor.red.cgColor {
  25. didSet {
  26. setNeedsDisplay()
  27. }
  28. }
  29. /// The progress ring end color.
  30. @objc open var endColor: CGColor = UIColor.blue.cgColor {
  31. didSet {
  32. setNeedsDisplay()
  33. }
  34. }
  35. /// The color of the background ring.
  36. @objc open var backgroundRingColor: CGColor? {
  37. didSet {
  38. setNeedsDisplay()
  39. }
  40. }
  41. /// The width of the progress ring.
  42. @objc open var ringWidth: CGFloat = 20 {
  43. didSet {
  44. setNeedsDisplay()
  45. }
  46. }
  47. /// The style of the progress line end (rounded or straight).
  48. @objc open var progressStyle: RingProgressViewStyle = .round {
  49. didSet {
  50. setNeedsDisplay()
  51. }
  52. }
  53. /// The opacity of the shadow under the progress end.
  54. @objc open var endShadowOpacity: CGFloat = 1.0 {
  55. didSet {
  56. endShadowOpacity = min(max(endShadowOpacity, 0.0), 1.0)
  57. setNeedsDisplay()
  58. }
  59. }
  60. /// Whether or not to hide the progress ring when progress is zero.
  61. @objc open var hidesRingForZeroProgress: Bool = false {
  62. didSet {
  63. setNeedsDisplay()
  64. }
  65. }
  66. /// Whether or not to allow anti-aliasing for the generated image.
  67. @objc open var allowsAntialiasing: Bool = true {
  68. didSet {
  69. setNeedsDisplay()
  70. }
  71. }
  72. /// The scale of the generated gradient image.
  73. /// Use lower values for better performance and higher values for more precise gradients.
  74. @objc open var gradientImageScale: CGFloat = 1.0 {
  75. didSet {
  76. setNeedsDisplay()
  77. }
  78. }
  79. /// The current progress shown by the view.
  80. /// Values less than 0.0 are clamped. Values greater than 1.0 present multiple revolutions of the progress ring.
  81. @NSManaged public var progress: CGFloat
  82. /// Disable actions for `progress` property.
  83. internal var disableProgressAnimation: Bool = false
  84. private let gradientGenerator = GradientGenerator()
  85. open override class func needsDisplay(forKey key: String) -> Bool {
  86. if key == "progress" {
  87. return true
  88. }
  89. return super.needsDisplay(forKey: key)
  90. }
  91. open override func action(forKey event: String) -> CAAction? {
  92. if !disableProgressAnimation, event == "progress" {
  93. if let action = super.action(forKey: "opacity") as? CABasicAnimation {
  94. let animation = action.copy() as! CABasicAnimation
  95. animation.keyPath = event
  96. animation.fromValue = presentation()?.value(forKey: event)
  97. animation.toValue = nil
  98. return animation
  99. } else {
  100. let animation = CABasicAnimation(keyPath: event)
  101. animation.duration = 0.001
  102. return animation
  103. }
  104. }
  105. return super.action(forKey: event)
  106. }
  107. open override func display() {
  108. contents = contentImage()
  109. }
  110. func contentImage() -> CGImage? {
  111. let size = bounds.size
  112. if #available(iOS 10.0, tvOS 10.0, *) {
  113. let format = UIGraphicsImageRendererFormat.default()
  114. let image = UIGraphicsImageRenderer(size: size, format: format).image { ctx in
  115. drawContent(in: ctx.cgContext)
  116. }
  117. return image.cgImage
  118. } else {
  119. UIGraphicsBeginImageContextWithOptions(size, false, 0)
  120. guard let ctx = UIGraphicsGetCurrentContext() else {
  121. return nil
  122. }
  123. drawContent(in: ctx)
  124. let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
  125. UIGraphicsEndImageContext()
  126. return image
  127. }
  128. }
  129. private func drawContent(in context: CGContext) {
  130. context.setShouldAntialias(allowsAntialiasing)
  131. context.setAllowsAntialiasing(allowsAntialiasing)
  132. let useGradient = startColor != endColor
  133. let squareSize = min(bounds.width, bounds.height)
  134. let squareRect = CGRect(x: (bounds.width - squareSize) / 2, y: (bounds.height - squareSize) / 2,
  135. width: squareSize, height: squareSize)
  136. let gradientRect = squareRect.integral
  137. let w = min(ringWidth, squareSize / 2)
  138. let r = min(bounds.width, bounds.height) / 2 - w / 2
  139. let c = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
  140. let p = max(0.0, disableProgressAnimation ? progress : presentation()?.progress ?? 0.0)
  141. let angleOffset = CGFloat.pi / 2
  142. let angle = 2 * .pi * p - angleOffset
  143. let minAngle = 1.1 * atan(0.5 * w / r)
  144. let maxAngle = 2 * .pi - 3 * minAngle - angleOffset
  145. let circleRect = squareRect.insetBy(dx: w / 2, dy: w / 2)
  146. let circlePath = UIBezierPath(ovalIn: circleRect)
  147. let angle1 = angle > maxAngle ? maxAngle : angle
  148. context.setLineWidth(w)
  149. context.setLineCap(progressStyle.lineCap)
  150. // Draw backdrop circle
  151. context.addPath(circlePath.cgPath)
  152. let bgColor = backgroundRingColor ?? startColor.copy(alpha: 0.15)!
  153. context.setStrokeColor(bgColor)
  154. context.strokePath()
  155. // Draw solid arc
  156. if angle > maxAngle {
  157. let offset = angle - maxAngle
  158. let arc2Path = UIBezierPath(arcCenter: c,
  159. radius: r,
  160. startAngle: -angleOffset,
  161. endAngle: offset,
  162. clockwise: true)
  163. context.addPath(arc2Path.cgPath)
  164. context.setStrokeColor(startColor)
  165. context.strokePath()
  166. context.translateBy(x: circleRect.midX, y: circleRect.midY)
  167. context.rotate(by: offset)
  168. context.translateBy(x: -circleRect.midX, y: -circleRect.midY)
  169. }
  170. // Draw shadow and progress end
  171. if p > 0.0 || !hidesRingForZeroProgress {
  172. context.saveGState()
  173. if endShadowOpacity > 0.0 {
  174. context.addPath(CGPath(__byStroking: circlePath.cgPath,
  175. transform: nil,
  176. lineWidth: w,
  177. lineCap: .round,
  178. lineJoin: .round,
  179. miterLimit: 0)!)
  180. context.clip()
  181. let shadowOffset = CGSize(width: w / 10 * cos(angle + angleOffset),
  182. height: w / 10 * sin(angle + angleOffset))
  183. context.setShadow(offset: shadowOffset,
  184. blur: w / 3,
  185. color: UIColor(white: 0.0, alpha: endShadowOpacity).cgColor)
  186. }
  187. let arcEnd = CGPoint(x: c.x + r * cos(angle1), y: c.y + r * sin(angle1))
  188. let shadowPath: UIBezierPath = {
  189. switch progressStyle {
  190. case .round:
  191. return UIBezierPath(ovalIn: CGRect(x: arcEnd.x - w / 2,
  192. y: arcEnd.y - w / 2,
  193. width: w,
  194. height: w))
  195. case .square:
  196. let path = UIBezierPath(rect: CGRect(x: arcEnd.x - w / 2,
  197. y: arcEnd.y - 2,
  198. width: w,
  199. height: 2))
  200. path.apply(CGAffineTransform(translationX: -arcEnd.x, y: -arcEnd.y))
  201. path.apply(CGAffineTransform(rotationAngle: angle1))
  202. path.apply(CGAffineTransform(translationX: arcEnd.x, y: arcEnd.y))
  203. return path
  204. }
  205. }()
  206. let shadowFillColor: CGColor = {
  207. let fadeStartProgress: CGFloat = 0.02
  208. if !hidesRingForZeroProgress || p > fadeStartProgress {
  209. return startColor
  210. }
  211. // gradually decrease shadow opacity
  212. return startColor.copy(alpha: p / fadeStartProgress)!
  213. }()
  214. context.addPath(shadowPath.cgPath)
  215. context.setFillColor(shadowFillColor)
  216. context.fillPath()
  217. context.restoreGState()
  218. }
  219. // Draw gradient arc
  220. let gradient: CGImage? = {
  221. guard useGradient else {
  222. return nil
  223. }
  224. let s = Float(1.5 * w / (2 * .pi * r))
  225. gradientGenerator.scale = gradientImageScale
  226. gradientGenerator.size = gradientRect.size
  227. gradientGenerator.colors = [endColor, endColor, startColor, startColor]
  228. gradientGenerator.locations = [0.0, s, 1.0 - s, 1.0]
  229. gradientGenerator.endPoint = CGPoint(x: 0.5 - CGFloat(2 * s), y: 1.0)
  230. return gradientGenerator.image()
  231. }()
  232. if p > 0.0 {
  233. let arc1Path = UIBezierPath(arcCenter: c,
  234. radius: r,
  235. startAngle: -angleOffset,
  236. endAngle: angle1,
  237. clockwise: true)
  238. if let gradient = gradient {
  239. context.saveGState()
  240. context.addPath(CGPath(__byStroking: arc1Path.cgPath,
  241. transform: nil,
  242. lineWidth: w,
  243. lineCap: progressStyle.lineCap,
  244. lineJoin: progressStyle.lineJoin,
  245. miterLimit: 0)!)
  246. context.clip()
  247. context.interpolationQuality = .none
  248. context.draw(gradient, in: gradientRect)
  249. context.restoreGState()
  250. } else {
  251. context.setStrokeColor(startColor)
  252. context.setLineWidth(w)
  253. context.setLineCap(progressStyle.lineCap)
  254. context.addPath(arc1Path.cgPath)
  255. context.strokePath()
  256. }
  257. }
  258. }
  259. }
  260. private extension RingProgressViewStyle {
  261. var lineCap: CGLineCap {
  262. switch self {
  263. case .round:
  264. return .round
  265. case .square:
  266. return .butt
  267. }
  268. }
  269. var lineJoin: CGLineJoin {
  270. switch self {
  271. case .round:
  272. return .round
  273. case .square:
  274. return .miter
  275. }
  276. }
  277. }