Interpolate Between Colors for UIScrollView

//define array with colors globally or locally let colorsArray: [UIColor] = [UIColor.flatRed(), UIColor.flatSky(), UIColor.flatMint(), UIColor.flatPlum(), UIColor.flatGreen(), UIColor.flatOrange(), UIColor.flatLime(), UIColor.flatNavy(), UIColor.flatYellow()] func interpolateColors(progress: CGFloat, light: Bool = false) -> UIColor { let progressInt: Int = Int(floor(progress)) var currentColor: UIColor = UIColor() //set up arrays for rgb color channels var r: [CGFloat] = [] var g: [CGFloat] = [] var b: [CGFloat] = [] for color in colorsArray{ let colorComponents = CGColorGetComponents(color.CGColor) r.append(colorComponents[0]) g.append(colorComponents[1]) b.append(colorComponents[2]) } var alpha: CGFloat = 1.0 if light { alpha = 0.4 } //if progress < 0 then array index out of range //in this case, return main red color if progress >= 0 { currentColor = UIColor(red: r[progressInt] - (progress-CGFloat(progressInt))*(r[progressInt]-r[progressInt+1]), green: g[progressInt] - (progress-CGFloat(progressInt))*(g[progressInt]-g[progressInt+1]), blue: b[progressInt] - (progress-CGFloat(progressInt))*(b[progressInt]-b[progressInt+1]), alpha: alpha) } else { currentColor = UIColor(red: 0.95, green: 0.38, blue: 0.35, alpha: alpha) } return currentColor }
This function returns a UIColor object based on the content offset of a UIScrollView.
Replace the values in the colors array with your own colors.

Have fun!

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.