2013-04-02 113 views
7

我試圖在drawRect中淡入一個UIColor到另一個。我已經創建這個功能在一定的百分比來計算顏色:從一個UIColor手動顏色褪色到另一個

- (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

你已經在最後幾行交換了你的綠色和藍色。

+0

噢,我的!這麼多的紅,綠,藍......我想我已經把他們全都直了!謝謝! – Luke

+0

沒問題。有時你只需要一雙額外的眼睛。 –

1

更新版本迅速

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) 
    } 
} 
相關問題