ios - 根据滚动逐渐改变背景颜色

标签 ios swift colors

我有一个 ScrollView ,当它向下滚动时背景会改变颜色。

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

我想设置 0% 和 100% 颜色,当前颜色将在 scrollViewDidScroll 上计算和设置

 0%               50%              100%
yellow           green             blue

编辑

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

最佳答案

这是 Swift 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)

关于ios - 根据滚动逐渐改变背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39778526/

相关文章:

wpf - 为每个角的边框设置不同的画笔颜色

java - Color == Robot.getPixelColor 结果为 false,即使它们是相同的颜色?

ios - 如何确定 Swift 3 中的属性或函数是否可用于 iOS 8

ios - 将更多数据嵌入到枚举案例中

objective-c - 将 macOS 目标添加到混合 iOS 项目中——为什么它找不到 Objective-C 符号?

iphone - 以编程方式更改 UIView 背景颜色

ios - 当我尝试拍摄屏幕快照(⌘+ S)时,iPhone模拟器崩溃了(使用libswiftFoundation.dylib插件)

ios - 是否有必要将 UITabBarController 委托(delegate)给 AppDelegate

ios - 如何使用调度或操作队列动态更改后台操作优先级。

ios - swift 1.2 Xcode 6.3 NSString?到字符串给线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x20)