2016-04-06 81 views
0

我創建下面的代碼一個漸變,我在另一個stackoverflow post發現瞭解iOS繪製徑向漸變定義顏色CGFloat的

- (void)drawInContext:(CGContextRef)ctx 
{ 
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"theme"] isEqualToString:@"black"]) { 

    } 

    size_t gradLocationsNum = 2; 
    CGFloat gradLocations[2] = {0.0f, 1.0f}; 
    CGFloat gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f}; 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum); 
    CGColorSpaceRelease(colorSpace); 

    CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height+100); 
    float gradRadius = MAX(self.bounds.size.width , self.bounds.size.height) ; 

    CGContextDrawRadialGradient(ctx, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation); 


    CGGradientRelease(gradient); 
} 

我不知道如何定義CGFloat gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f};,這樣我可以做是這樣的:

CGFloat gradColors[8]; 

if ... 
    gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f}; 
else if ... 
    gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f}; 

另外:是有辦法一個UIColor轉換爲這種格式?

回答

1

您可以嘗試使用接受CGColor數組的CGGradientCreateWithColors()

例如。

CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)@[(id)aUIColor1.CGColor, (id)aUIColor2.CGColor], gradientLocations);