我试图向我的 UIView 添加阴影,但在我的 drawRect 方法中我得到了 EXC_BAD_ACCESS。
(我用的是ARC)
-(void) drawRect:(CGRect)rect {
CGColorRef lightColor = [UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8].CGColor;
CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw shadow
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, CGSizeMake(-5, 0), 10, shadowColor);
CGContextSetFillColorWithColor(context, lightColor);
CGContextFillRect(context, _coloredBoxRect);
CGContextRestoreGState(context);
}
错误信息:线程 1:程序收到信号:“EXC_BAD_ACCESS”。
Line: CGContextSetFillColorWithColor(context, lightColor);
当我将此行更改为:
[[UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8] setFill];
我得到同样的错误,但在这一行:
CGContextSetShadowWithColor(context, CGSizeMake(-5, 0), 10, shadowColor);
Update我最终通过更改解决了这个问题:
CGColorRef ShadowColor = [UIColor colorWithRed:0.2 绿色:0.2 蓝色:0.2 alpha:0.4].CGColor;
to
浮动组件[4] = {0, 0, 0, 1.0/3.0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef ShadowColor = CGColorCreate( colorSpace, 组件);
最终(工作)代码:
-(void) drawRect:(CGRect)rect
{
float components[4] = {0, 0, 0, 1.0/3.0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef shadowColor = CGColorCreate( colorSpace, components);
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw shadow
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, CGSizeMake(-5, 0), 10, shadowColor);
CGContextSetFillColorWithColor(context, lightColor);
[[UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8] setFill];
CGContextRestoreGState(context);
}