这是我在 UIView 子类中用来轻松添加渐变视图的代码:
#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 中它工作正常,有什么建议吗?