Search code examples
objective-ciosquartz-2dcgcontext

CGContextStrokePath(context) crashes. Why?


I'm new to Quartz 2D and the world of contexts. why is this code crashing ?

NSMutableData* pdfData = [[NSMutableData alloc] initWithLength:1000];

CGRect bounds = (CGRectMake(100, 100, 100, 100));
NSDictionary* documentInfo = nil;

UIGraphicsBeginPDFContextToData (pdfData,
                                 bounds,
                                 documentInfo);

CGContextRef context = UIGraphicsGetCurrentContext();
NSLog (@"context: %@", context);

// Drawing lines with a white stroke color
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
// Draw them with a 2.0 stroke width so they are a bit more visible.
CGContextSetLineWidth(context, 2.0);

// Draw a single line from left to right
CGContextMoveToPoint(context, 10.0, 30.0);
CGContextAddLineToPoint(context, 310.0, 30.0);
CGContextStrokePath(context);

[pdfData release];

The code crashes at CGContextStrokePath(context) with EXC_BAD_ACCESS

Thank you.


Solution

  • Before you draw to a PDF graphics context, you need to create a page with UIGraphicsBeginPDFPage or UIGraphicsBeginPDFPageWithInfo.

    CGRect bounds = CGRectMake(0, 0, 100, 100);
    UIGraphicsBeginPDFContextToData(pdfData, bounds, nil);
    UIGraphicsBeginPDFPage(bounds, nil);