2012-06-07 20 views
0

这是我在一个UIView子类使用的代码可以轻松地添加渐变观点:CGGradientCreateWithColors不工作的iOS 4了

#import "GradientView.h" 


@implementation GradientView 

@synthesize direction, startColor, endColor; 

-(id)initWithFrame:(CGRect)frame startColor:(UIColor *)start_color endColor:(UIColor *)end_color direction:(GradientDirection)gradient_direction 
{ 
    if((self = [super initWithFrame:frame])) 
    { 
    self.startColor = start_color; 
    self.endColor = end_color; 
    self.direction = gradient_direction; 
    } 
    return self; 
} 

- (id)initWithFrame:(CGRect)frame 
{ 
    [self doesNotRecognizeSelector:_cmd]; 
    return self; 
} 

-(void)drawRect:(CGRect)rect 
{ 
    CGColorRef start_color = [self.startColor CGColor]; 
    CGColorRef end_color = [self.endColor CGColor]; 

    NSArray *colors = [NSArray arrayWithObjects:(__bridge id)start_color, (__bridge id)end_color, nil]; 
    CGFloat locations[] = {0,1}; 
    CGGradientRef gradient = CGGradientCreateWithColors(CGColorGetColorSpace(start_color), (__bridge CFArrayRef)colors, locations); 
    CGRect bounds = self.bounds; 
    CGPoint start; 
    CGPoint end; 
    if(direction == GradientLeftToRight) 
    { 
    start = CGPointMake(bounds.origin.x, CGRectGetMidY(bounds)); 
    end = CGPointMake(CGRectGetMaxX(bounds), CGRectGetMidY(bounds)); 
    } 
    else 
    { 
    start = CGPointMake(CGRectGetMidX(bounds), bounds.origin.y); 
    end = CGPointMake(CGRectGetMidX(bounds), CGRectGetMaxY(bounds)); 
    } 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextDrawLinearGradient(context, gradient, start, end, 0); 
    CGGradientRelease(gradient); 
} 

@end 

它在早期版本的Xcode工作得十分完美,但是当我上的iOS4.3运行现在它只是显示为黑色。在iOS 5中,它工作正常,有什么建议吗?

回答

3

我在创建一个带有UIGraphicsBeginImageContextWithOptions(...)的RGBA图像上下文时遇到了类似的问题。

在我的情况下,我使用梯度停止创建与[UIColor colorWithWhite:alpha:]。在iOS 5上工作得很好,但在iOS 4上没有问题。当我使用[UIColor colorWithRed:green:blue:alpha](并将相同的值应用于红色,绿色和蓝色通道)创建渐变停止时,它开始在iOS 4上工作。

我怀疑它有处理iOS 4背后的不兼容的色彩空间。或许colorWithWhite:alpha:正在使用“灰色”色彩空间,当上下文位于RGB色彩空间中时,该色彩空间无法工作。