JXSegmentedViewTool.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // JXSegmentedViewTool.swift
  3. // JXSegmentedView
  4. //
  5. // Created by jiaxin on 2018/12/26.
  6. // Copyright © 2018 jiaxin. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. public extension UIColor {
  11. var jx_red: CGFloat {
  12. var r: CGFloat = 0
  13. getRed(&r, green: nil, blue: nil, alpha: nil)
  14. return r
  15. }
  16. var jx_green: CGFloat {
  17. var g: CGFloat = 0
  18. getRed(nil, green: &g, blue: nil, alpha: nil)
  19. return g
  20. }
  21. var jx_blue: CGFloat {
  22. var b: CGFloat = 0
  23. getRed(nil, green: nil, blue: &b, alpha: nil)
  24. return b
  25. }
  26. var jx_alpha: CGFloat {
  27. return cgColor.alpha
  28. }
  29. }
  30. public class JXSegmentedViewTool {
  31. public static func interpolate<T: SignedNumeric & Comparable>(from: T, to: T, percent: T) -> T {
  32. let percent = max(0, min(1, percent))
  33. return from + (to - from) * percent
  34. }
  35. public static func interpolateColor(from: UIColor, to: UIColor, percent: CGFloat) -> UIColor {
  36. let r = interpolate(from: from.jx_red, to: to.jx_red, percent: percent)
  37. let g = interpolate(from: from.jx_green, to: to.jx_green, percent: CGFloat(percent))
  38. let b = interpolate(from: from.jx_blue, to: to.jx_blue, percent: CGFloat(percent))
  39. let a = interpolate(from: from.jx_alpha, to: to.jx_alpha, percent: CGFloat(percent))
  40. return UIColor(red: r, green: g, blue: b, alpha: a)
  41. }
  42. public static func interpolateColors(from: [CGColor], to: [CGColor], percent: CGFloat) -> [CGColor] {
  43. var resultColors = [CGColor]()
  44. for index in 0..<from.count {
  45. let fromColor = UIColor(cgColor: from[index])
  46. let toColor = UIColor(cgColor: to[index])
  47. let r = interpolate(from: fromColor.jx_red, to: toColor.jx_red, percent: percent)
  48. let g = interpolate(from: fromColor.jx_green, to: toColor.jx_green, percent: CGFloat(percent))
  49. let b = interpolate(from: fromColor.jx_blue, to: toColor.jx_blue, percent: CGFloat(percent))
  50. let a = interpolate(from: fromColor.jx_alpha, to: toColor.jx_alpha, percent: CGFloat(percent))
  51. resultColors.append(UIColor(red: r, green: g, blue: b, alpha: a).cgColor)
  52. }
  53. return resultColors
  54. }
  55. }