2016-09-29 113 views
2

我有一个滚动视图,当它向下滚动时,背景会改变颜色。逐渐改变基于滚动的背景颜色

我知道我可以使用UIView动画来使这个自动。但我想根据滚动的百分比设置颜色。

我想设定0%和100点%的色彩和当前颜色将被计算并基于对scrollViewDidScroll

0%    50%    100% 
yellow   green    blue 

编辑

如何计算新的颜色设置滚动位置?

+0

确定一个解决方案,什么是你的问题? – rmaddy

+0

如何根据滚动位置计算新颜色 –

+0

您需要哪些帮助?你知道如何计算滚动比例吗?你的问题只是关于颜色?首先回答10%,25%,75%等你想要的颜色。我不知道任何标准的进展从黄色变为绿色变为蓝色。 – rmaddy

回答

12

下面是斯威夫特3.

// This function calculates a new color by blending the two colors. 
// A percent of 0.0 gives the "from" color 
// A percent of 1.0 gives the "to" color 
// Any other percent gives an appropriate color in between the two 
func blend(from: UIColor, to: UIColor, percent: Double) -> UIColor { 
    var fR : CGFloat = 0.0 
    var fG : CGFloat = 0.0 
    var fB : CGFloat = 0.0 
    var tR : CGFloat = 0.0 
    var tG : CGFloat = 0.0 
    var tB : CGFloat = 0.0 

    from.getRed(&fR, green: &fG, blue: &fB, alpha: nil) 
    to.getRed(&tR, green: &tG, blue: &tB, alpha: nil) 

    let dR = tR - fR 
    let dG = tG - fG 
    let dB = tB - fB 

    let rR = fR + dR * CGFloat(percent) 
    let rG = fG + dG * CGFloat(percent) 
    let rB = fB + dB * CGFloat(percent) 

    return UIColor(red: rR, green: rG, blue: rB, alpha: 1.0) 
} 

// Pass in the scroll percentage to get the appropriate color  
func scrollColor(percent: Double) -> UIColor { 
    var start : UIColor 
    var end : UIColor 
    var perc = percent 
    if percent < 0.5 { 
     // If the scroll percentage is 0.0..<0.5 blend between yellow and green 
     start = UIColor.yellow 
     end = UIColor.green 
    } else { 
     // If the scroll percentage is 0.5..1.0 blend between green and blue 
     start = UIColor.green 
     end = UIColor.blue 
     perc -= 0.5 
    } 

    return blend(from: start, to: end, percent: perc * 2.0) 
} 

// In your "scrollViewDidScroll" delegate, calculate the scroll 
// percentage as a value from 0.0 to 1.0 
// Then call "scrollColor" 
let scrollPercentage = ... // your calculation 
let scrollColor = scrollColor(percent: scrollPercentage) 
+1

谢谢。 “混合(from:to:percent:)”对我的需求来说是完美的 –