[英]EXC_BAD_ACCES drawing shadow
我正在嘗試向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);
}
啟用ARC時, UIColor
可能不會使其進入自動釋放池。 如果未將其放置在池中並立即釋放,則您引用的CGColor
(lightColor,shadowColor)也將在您傳遞它時被釋放,因為它們由UIColor
擁有/擁有,並且未采取任何措施確保這些(非NSObject
)引用在該范圍之外仍然有效。
我無法復制您的確切問題,但可以使用以下方法復制:
CGColorRef shadowColor =
[[UIColor alloc] initWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;
在sim v5.0上運行時。
您是否張貼了確切的例子? 您正在運行什么操作系統版本? 它在所有OS版本中都發生嗎? 也許您應該看看自動販賣機。
或者,您可以告訴編譯器將UIColor
對象添加到自動釋放池中,而不是立即釋放它們。
UIColor * __autoreleasing lightUIColor = [UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8];
CGColorRef lightColor = lightUIColor.CGColor;
UIColor * __autoreleasing shadowUIColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.4];
CGColorRef shadowColor = shadowUIColor.CGColor;
我看不到為什么會崩潰的任何原因,但是嘗試使用此代碼而不是CGColorRef設置顏色。 如果它不能解決崩潰問題,至少您會知道那不是問題所在:
[[UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8] setFill];
以下代碼將滿足ARC:
UIColor *lightColor = [UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8];
...
CGContextSetFillColorWithColor(context, lightColor.CGColor);
ARC在創建臨時UIColor *對象后立即釋放它的崩潰原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.