我有一个 ARC 项目,正在尝试绘制垂直线性渐变。下面的代码适用于模拟器,但在设备上测试时会引发内存/EXC_BAD_ACCESS
错误。该应用程序在以下两行代码中崩溃:
NSArray *colorArray = [NSArray arrayWithObjects:(__bridge id)topColor, (__bridge id)bottomColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colorArray, colorLocations);
这两行代码取自以下代码(仅供参考):
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[self createGradientForContext:context andView:self.captionView];
[self createGradientForContext:context andView:self.linksView];
[self createGradientForContext:context andView:self.commentView];
}
- (void)createGradientForContext:(CGContextRef)context andView:(UIView *)view
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat colorLocations[] = { 0.0f, 1.0f };
CGColorRef topColor = [[UIColor colorWithRed:51.0f/255.0f green:51.0f/255.0f blue:51.0f/255.0f alpha:1.0f] CGColor];
CGColorRef bottomColor = [[UIColor colorWithRed:48.0f/255.0f green:48.0f/255.0f blue:48.0f/255.0f alpha:1.0f] CGColor];
NSArray *colorArray = [NSArray arrayWithObjects:(__bridge id)topColor, (__bridge id)bottomColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge_retained CFArrayRef) colorArray, colorLocations);
CGRect frame = view.frame;
CGPoint startPoint = CGPointMake(CGRectGetMidX(frame), CGRectGetMinY(frame));
CGPoint endPoint = CGPointMake(CGRectGetMidX(frame), CGRectGetMaxY(frame));
CGContextSaveGState(context);
CGContextAddRect(context, frame);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
提前感谢任何和所有的指导。