逐渐根据滚动更改背景颜色 [英] Gradually change background color based on scroll
本文介绍了逐渐根据滚动更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个滚动视图,当它向下滚动时,背景会改变颜色。
I have a scrollview that when it is scrolled down the background changes color.
我知道我可以使用UIView动画来实现这一点。但是我想根据滚动的百分比设置一种颜色。
I know I could use UIView animations to make this automatic. But I want to set a color based on the percentage of the scroll.
我想设置0%和100%颜色,当前颜色将被计算和设置on scrollViewDidScroll
I want set the 0% and the 100% colors and the current color would be calculated and set on scrollViewDidScroll
0% 50% 100%
yellow green blue
编辑
如何根据滚动位置计算新颜色?
How can I calculate the new color based on the scroll position?
推荐答案
这是Swift 3的解决方案。
Here's a solution for 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)
这篇关于逐渐根据滚动更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文