Make background color change during scroll

前端 未结 5 1947
太阳男子
太阳男子 2021-01-14 07:10

I have an onboarding section of my app with 4 pages the users scrolls through horizontally to get an idea of how to use the app (standard). I want the background color to tr

5条回答
  •  难免孤独
    2021-01-14 07:40

        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)
        }
    

提交回复
热议问题