EXC_BAD_ACCES绘制阴影

Thy*_*hys 3 core-graphics uiview cgcontext ios automatic-ref-counting

我想为我的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);
}
Run Code Online (Sandbox Code Playgroud)

错误消息: 线程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];
Run Code Online (Sandbox Code Playgroud)

我得到了相同的错误,但在这一行:

CGContextSetShadowWithColor(context, CGSizeMake(-5, 0), 10, shadowColor);
Run Code Online (Sandbox Code Playgroud)

更新 我最终通过更改解决了问题:

CGColorRef shadowColor = [UIColor colorWithRed:0.2绿色:0.2蓝色:0.2 alpha:0.4] .CGColor;

float components [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);
}
Run Code Online (Sandbox Code Playgroud)

jus*_*tin 5

UIColor启用ARC后,可能无法将其设置为自动释放池.如果它没有被放入池中并立即释放,那么CGColor你引用的s(lightColor,shadowColor)也会在你传递它时被解除分配,因为它们被持有/拥有UIColor,并且没有采取任何措施来确保这些(非NSObject)引用在该范围之外仍然有效.

我无法重现您的确切问题,但我可以使用以下方法重现它:

CGColorRef shadowColor =
  [[UIColor alloc] initWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;
Run Code Online (Sandbox Code Playgroud)

在sim v5.0上运行时.

你发布了确切的例子吗?您运行的操作系统版本是什么?是否会在所有操作系统版本中发生?也许你应该看看asm.