2012-12-28 81 views
2

我正在使用某種顏色在一個CALayers上繪製線性漸變,但隨機地使用相同的輸入,顏色在屏幕上以粉紅色繪製。CALayer:線性漸變問題

的代碼如下:

bottomComponents = bottomColor.colorComponents; 
topComponents = topColor.colorComponents; 
middleComponents = middleColor.colorComponents; 

CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

CGGradientRef glossGradient; 
CGColorSpaceRef rgbColorspace; 

size_t numberOfLocations = 3; 
CGFloat locations[3] = {0.0f, MIDDLE_POINT, 1.0f}; 
CGFloat components[12] = 
{ 
    topComponents.red, topComponents.green, topComponents.blue, topComponents.alpha, 
    middleComponents.red, middleComponents.green, middleComponents.blue, middleComponents.alpha, 
    bottomComponents.red, bottomComponents.green, bottomComponents.blue, bottomComponents.alpha 
}; 

rgbColorspace = CGColorSpaceCreateDeviceRGB(); 
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, numberOfLocations); 

CGRect currentBounds = self.bounds; 
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f); 
CGPoint bottomCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetHeight(currentBounds)); 
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, bottomCenter, 0); 

CGGradientRelease(glossGradient); 
CGColorSpaceRelease(rgbColorspace); 

colorComponents剛剛返回與顏色成分的結構體。

當我在日誌中輸出顏色時,它是正確的顏色,但是當它顯示在屏幕上時,無論啓動顏色如何,它都是粉紅色的。

有什麼我做錯了,可能會導致隨機粉紅色出現?

粉紅色完全偶爾出現。我會從相同的值加載,很少,但肯定會顯示爲粉紅色。從不同的值加載產生相同的結果。它發生在大約1-2%的時間。

+0

我沒有看到任何錯誤。您是將顏色值作爲完整的RGBA傳遞還是將UIColor類方法用於預定義的值? – Lefteris

+0

@Lefteris我將它們作爲完整的RGBA傳遞給他們。那太糟糕了。有一次,我希望自己錯了。 – RileyE

+0

您是否遇到過設備或模擬器上的問題?你能發佈正常和粉紅色漸變的截圖嗎? – Lefteris

回答

0

有些時候你使用UIColor預定義的顏色會有機會嗎? (例如greenColor) 我發現那些不生成適當的組件。

Liviu

+0

我不確定爲什麼我沒有收到堆棧交換通知。抱歉。我在任何時候都不使用UIColor預定義的顏色,因爲我所有的顏色都來自服務器,我將它們解析爲自己的顏色。然而,當我解析顏色時,數據是正確的,當我把它放到日誌裏。不過謝謝你的想法。 – RileyE