8

我正在尝试UIColordrawRect. 我创建了这个函数来计算一定百分比的颜色:

- (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];
}

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

它有点工作,但不会[UIColor purpleColor]正确褪色[UIColor redColor]。在 0.1% 时,它显示为绿色而不是紫色,因此它似乎从绿色变为红色,而不是从紫色变为红色。

有人知道我在做什么错吗?这是计算这个错误的方法吗?有没有更准确的方法来做到这一点?

4

2 回答 2

6

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

于 2013-04-02T06:54:01.023 回答
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)
    }
}
于 2016-12-07T15:15:12.040 回答