Skip to content

Instantly share code, notes, and snippets.

@masuhara
Last active May 6, 2018 20:33
Show Gist options
  • Save masuhara/597a3db7c485d5d653d1ece2e2f6d40e to your computer and use it in GitHub Desktop.
Save masuhara/597a3db7c485d5d653d1ece2e2f6d40e to your computer and use it in GitHub Desktop.
Rainbow color gradient written in Swift2.2
func insertGradientLayer(view: UIView) {
let color1 = UIColor.redColor()
let color2 = UIColor(red: 255, green: 165, blue: 0, alpha: 1.0)
let color3 = UIColor.yellowColor()
let color4 = UIColor(red: 0, green: 128, blue: 0, alpha: 1.0)
let color5 = UIColor.cyanColor()
let color6 = UIColor.blueColor()
let color7 = UIColor.purpleColor()
let fromColors = [color1.CGColor, color2.CGColor, color3.CGColor, color4.CGColor, color5.CGColor, color6.CGColor, color7.CGColor]
let toColors = fromColors.reverse()
let animation = CABasicAnimation(keyPath: "colors")
animation.duration = 1.0
animation.repeatCount = 99999
// animation.autoreverses = true
// animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.fromValue = fromColors
animation.toValue = Array(toColors)
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = fromColors
gradient.addAnimation(animation, forKey: "colors")
view.layer.insertSublayer(gradient, atIndex: 0)
}
@masuhara
Copy link
Author

masuhara commented Jul 10, 2016

.CGColorを忘れると、「Error: CGColorSpaceIsUncalibrated」で死ぬ

@dkarbayev
Copy link

Wow, praise the Internet! Man, you saved me a ton of nerves even though I don't understand japanese. Just googled for CGColorSpaceIsUncalibrated error and stumbled upon your comment. Used google translate to check what you've written, then checked my code and TADA! Turned out I forgot to add .cgColor in couple of places so my app crashed during animation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment