var currPage = 0
let colors: [UIColor] = [.red, .blue, .green, .yellow, .purple, .orange]
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// for horizontal scrolling
let progress = scrollView.contentOffset.x / scrollView.bounds.width
let page = Int(progress)
if currPage != page { currPage = page }
let nextPage = Int(progress + 1)
let prog = 1 - (CGFloat(Int(progress + 1)) - progress)
print("\(currPage) \(nextPage) \(prog)")
if currPage >= 0 && currPage < colors.count && nextPage >= 0 && nextPage < colors.count {
let interColor = colorBetween(col1: colors[currPage], col2: colors[nextPage], percent: prog)
scrollView.backgroundColor = interColor.withAlphaComponent(0.5)
}
}
// calculates intermediate color, percent should in between 0.0 - 1.0
func colorBetween(col1: UIColor, col2: UIColor, percent: CGFloat) -> UIColor {
let c1 = CIColor(color: col1)
let c2 = CIColor(color: col2)
let alpha = (c2.alpha - c1.alpha) * percent + c1.alpha
let red = (c2.red - c1.red) * percent + c1.red
let blue = (c2.blue - c1.blue) * percent + c1.blue
let green = (c2.green - c1.green) * percent + c1.green
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
Edit:
Another type of calculation
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let progress = scrollView.contentOffset.x / scrollView.bounds.width
let page = CGFloat(round(progress))
let move = progress - page
let nextPage = Int(move < 0 ? page + floor(move) : page + ceil(move))
let currPage = Int(page)
print(currPage, nextPage)
if currPage >= 0, currPage < colors.count, nextPage >= 0, nextPage < colors.count {
let interColor = colorBetween(col1: colors[currPage], col2: colors[nextPage], percent: abs(move))
scrollView.backgroundColor = interColor.withAlphaComponent(0.5)
}
}