【发布时间】:2012-02-16 23:54:09
【问题描述】:
我正在尝试向我的 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”。
线路: 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);
更新 我终于通过更改解决了这个问题:
CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;
到
浮动组件[4] = {0, 0, 0, 1.0/3.0}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGColorRef shadowColor = CGColorCreate(colorSpace, components);
最终(工作)代码:
-(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);
}
【问题讨论】:
-
在此处发布确切的错误消息。
-
错误信息并没有真正的帮助,但为了您的舒适(见编辑)。
-
你的调试器至少应该告诉你哪一行崩溃了。
-
drawRect 在绘制 UIView 时由 iOS 自己调用。
-
它在 CGContextSetFillColorWithColor 上崩溃
标签: ios uiview core-graphics automatic-ref-counting cgcontext