我正在尝试编写用于在Quartz 2d中绘图的代码。当触摸在屏幕上移动时,将重复调用drawToPoint:方法。因此,我不必重复重新创建上下文,我持有对绘图创建的上下文的引用。当我在drawToPoint:方法中创建另一个上下文“Create a new Context”时,如下例所示,代码崩溃时出现EXC_BAD_ACCESS而控制台上没有任何内容。此外,代码在drawToPoint:方法的第二次调用时崩溃,原因是我持有引用的上下文的某些损坏(此上下文在整个类中的任何其他位置都没有触及)。在下面的代码中,如果我注释掉标记为“创建新上下文”的代码部分,一切正常。为什么在绘图时创建新的上下文会导致崩溃?谢谢你的帮助。
- (CGContextRef)createContextWithSize:(CGSize)lstructSize
{
NSMutableData *data = [NSMutableData dataWithLength:lstructSize.width * lstructSize.height * 4];
CGContextRef lrefContext = CGBitmapContextCreate([data mutableBytes],
lstructSize.width,
lstructSize.height,
8,
lstructSize.width * 4,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedLast);
if (lrefContext == nil)
{
NSLog(@"%@ : Context is Nil", NSStringFromClass([self class]));
}
return lrefContext;
}
- (void)drawToPoint:(CGPoint)lstructPoint
{
CGContextRef lrefContext = nil;
UIGraphicsPushContext(self.refContext);
{
lrefContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(lrefContext);
{
CGContextScaleCTM(lrefContext, 1.0, -1.0);
CGContextTranslateCTM( lrefContext, 0, -self.structSize.height);
// Draw ine to the new Point
{
CGContextMoveToPoint(lrefContext, self.structLastPoint.x, self.structLastPoint.y);
CGContextAddLineToPoint(lrefContext, lstructPoint.x, lstructPoint.y);
CGContextSetLineCap(lrefContext, kCGLineCapRound);
CGContextSetLineWidth(lrefContext, 5.0);
CGContextSetRGBStrokeColor(lrefContext, 1.0, 0.0, 0.0, 1.0);
CGContextStrokePath(lrefContext);
}
// Save the new Image
{
lrefContext = UIGraphicsGetCurrentContext();
if (lrefContext)
{
self.objImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(lrefContext)];
if (self.objImage == nil)
{
NSLog(@"No Image Painted");
}
}
}
// Create a New Context
{
CGContextRef lrefCompositeContext = [self createContextWithSize:CGSizeMake(self.structSize.width, self.structSize.height)];
{
UIGraphicsPushContext(lrefCompositeContext);
{
lrefCompositeContext = UIGraphicsGetCurrentContext();
}
UIGraphicsPopContext();
}
CGContextRelease(lrefCompositeContext);
}
// Update Last Point
{
self.structLastPoint = lstructPoint;
}
}
CGContextRestoreGState(lrefContext);
}
UIGraphicsPopContext();
}