Kodeco Forums

Video Tutorial: Intermediate iOS Animation Part 9: Gradient Animations

In this video tutorial you'll learn about CAGradientLayer and how to create animations with it.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3270-intermediate-ios-animation/lessons/10

Map is great way to get from UIColor to CGColor, got me thinking why does CGColor not have nnnColor() functions. I don’t think it is better than using map, just for fun I tried making an extension of CGColor.

extension CGColor {
  class func whiteColor() -> CGColor {
    return UIColor.whiteColor().CGColor
  }
  class func blackColor() -> CGColor {
    return UIColor.blackColor().CGColor
  }
}

Now I can use:

gradientLayer.colors = [CGColor.blackColor(), CGColor.whiteColor(), CGColor.blackColor()]

Thanks for great tutorial.

1 Like

While I don’t think that it makes sense for those convenience functions to actually be functions –they should be static properties– that’s what we’ve got to work with. To avoid having to recreate every single one of them, I would recommend this…

extension CGColor {
  init(uIColor: UIColor) {
    self = uIColor.CGColor
  }
}

but CGColor is old, and therefore not a struct, so you can’t. You can, however, do this:

func CGColor(uIColor: UIColor) -> CGColor {
  return uIColor.CGColor
}

which allows you to leave off the UIColor…

CGColor(.whiteColor())
CGColor(.blackColor())

…but it doesn’t autocomplete, and I don’t think it’s better than the clarity of

UIColor.whiteColor().CGColor
UIColor.blackColor().CGColor

Let’s wait until WWDC and see if CGColor and UIColor are implicitly convertible to each other. For now, I think what Marin did is almost optimal. As long as UIColor is explicitly used on one argument, the compiler will know what they all are, so it can be cleaned up like this:

gradientLayer.colors = [UIColor
  .yellowColor(),
  .greenColor(),
  .orangeColor(),
  .cyanColor(),
  .redColor(),
  .yellowColor()
].map{$0.CGColor}

But again, autocomplete is currently not smart enough to deal with that. That said, as the code will be read more than it is written, I’d make it look like this anyway.