Reputation: 477
this is the code I use in a UIView subclass to easily add gradient views:
#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
It worked flawlessly in earlier xcode versions, but when I run it on iOS4.3 now it's just displaying as black. In iOS 5 it works fine, any suggestions?
Upvotes: 0
Views: 673
Reputation: 964
I had a similar problem when creating a RGBA image context with UIGraphicsBeginImageContextWithOptions(...)
.
In my case, I was using gradient stops were created with [UIColor colorWithWhite:alpha:]
. Worked fine on iOS 5, but not on iOS 4. When I created the gradient stops with [UIColor colorWithRed:green:blue:alpha]
(and the same value applied to red, green and blue channels) then it started working on iOS 4.
I suspect it has to do with an incompatible colorspace behind the scenes on iOS 4. Perhaps colorWithWhite:alpha:
is using a "Gray" colorspace, that fails to work when the context is in the RGB colorspace.
Upvotes: 3