手动从一个UIColor褪色到另一个UIColor

时间:2013-04-02 06:49:41

标签: ios colors drawrect uicolor cgcolor

我正试图在UIColor中将一个drawRect淡化为另一个- (UIColor *)colorFromColor:(UIColor *)fromColor toColor:(UIColor *)toColor percent:(float)percent { float dec = percent / 100.f; CGFloat fRed, fBlue, fGreen, fAlpha; CGFloat tRed, tBlue, tGreen, tAlpha; CGFloat red, green, blue, alpha; if(CGColorGetNumberOfComponents(fromColor.CGColor) == 2) { [fromColor getWhite:&fRed alpha:&fAlpha]; fGreen = fRed; fBlue = fRed; } else { [fromColor getRed:&fRed green:&fGreen blue:&fBlue alpha:&fAlpha]; } if(CGColorGetNumberOfComponents(toColor.CGColor) == 2) { [toColor getWhite:&tRed alpha:&tAlpha]; tGreen = tRed; tBlue = tRed; } else { [toColor getRed:&tRed green:&tGreen blue:&tBlue alpha:&tAlpha]; } red = (dec * (tRed - fRed)) + fRed; blue = (dec * (tGreen - fGreen)) + fGreen; green = (dec * (tBlue - fBlue)) + fBlue; alpha = (dec * (tAlpha - fAlpha)) + fAlpha; return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } 。我创建了这个函数来计算某个百分比的颜色:

[UIColor purpleColor]

这样做取每个R / G / B / A值并根据百分比递增它。

它有用,但不能正确地将[UIColor redColor]淡化为{{1}}。在0.1%时,它显示为绿色而不是紫色,因此它看起来从绿色变为红色而不是从紫色变为红色。

任何人都知道我做错了什么?这是计算这个的错误方法吗?有更准确的方法吗?

2 个答案:

答案 0 :(得分:4)

你在最后几行换了你的绿色和蓝色。

答案 1 :(得分:2)

swift的更新版本

import UIKit

extension UIColor {
    // MARK: - UIColor+Percentage


    class func colorForProgress(progress:CGFloat) -> UIColor {

        var normalizedProgress = progress < 0 ?  0 : progress
        normalizedProgress = normalizedProgress > 1 ?  1 : normalizedProgress

        let R:CGFloat = 155.0 * normalizedProgress
        let G:CGFloat = 155.0 * (1 - normalizedProgress) 
        let B:CGFloat = 0.0

        return UIColor(red: R / 255.0, green: G / 255.0, blue: B / 255.0, alpha: 1)
    }

    class func transitionColor(fromColor:UIColor, toColor:UIColor, progress:CGFloat) -> UIColor {    

        var percentage = progress < 0 ?  0 : progress
        percentage = percentage > 1 ?  1 : percentage

        var fRed:CGFloat = 0
        var fBlue:CGFloat = 0
        var fGreen:CGFloat = 0
        var fAlpha:CGFloat = 0

        var tRed:CGFloat = 0
        var tBlue:CGFloat = 0
        var tGreen:CGFloat = 0
        var tAlpha:CGFloat = 0

        fromColor.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha)
        toColor.getRed(&tRed, green: &tGreen, blue: &tBlue, alpha: &tAlpha)

        let red:CGFloat = (percentage * (tRed - fRed)) + fRed;
        let green:CGFloat = (percentage * (tGreen - fGreen)) + fGreen;
        let blue:CGFloat = (percentage * (tBlue - fBlue)) + fBlue;
        let alpha:CGFloat = (percentage * (tAlpha - fAlpha)) + fAlpha;

        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
}