我试图动态淡化PageViewController
中的背景色。我想将页面上的颜色淡化为另一种颜色。
到目前为止,我尝试通过实现函数scrollView
并设置PageViewController
的背景色来利用scrollViewDidScroll
的基础scrollview
。
看看下面的代码:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
guard lowerIndex >= 0, upperIndex < colors.count else { return }
let percentComplete = (offset / CGFloat(colors.count)) / (scrollView.frame.width / CGFloat(colors.count))
scrollView.backgroundColor = fadeFromColor(fromColor: colorCurrent, toColor: colorAfter, withPercentage: percentComplete)
}
此函数使用自定义函数fadeFromColor,其定义如下:
func fadeFromColor(fromColor: UIColor, toColor: UIColor, withPercentage: CGFloat) -> UIColor {
var fromRed: CGFloat = 0.0
var fromGreen: CGFloat = 0.0
var fromBlue: CGFloat = 0.0
var fromAlpha: CGFloat = 0.0
fromColor.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha)
var toRed: CGFloat = 0.0
var toGreen: CGFloat = 0.0
var toBlue: CGFloat = 0.0
var toAlpha: CGFloat = 0.0
toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha)
// calculate the actual RGBA values of the fade colour
let red = (toRed - fromRed) * withPercentage + fromRed
let green = (toGreen - fromGreen) * withPercentage + fromGreen
let blue = (toBlue - fromBlue) * withPercentage + fromBlue
let alpha = (toAlpha - fromAlpha) * withPercentage + fromAlpha
// return the fade colour
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
目前,我无法在正确的时间获得正确的颜色。 您有更好的主意来解决我的问题吗?还是您认为至少我的想法是正确的?