Search code examples
iosobjective-cquartz-2d

IOS Quartz2D cannot get image from current context


What am I missing? Been stuck for several hours, drawRect draws as expected, getTheImage() is called from a viewcontoller UIGraphicsGetImageFromCurrentImageContext() returns nil; tried many variations. Any help is appreciated.

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextSetLineWidth(context, 5.0);
    CGContextSetStrokeColorWithColor(context, [[UIColor    blackColor]CGColor]);
    CGContextMoveToPoint(context,100.0,100.0);
    CGContextAddLineToPoint(context,200.0,200.0);
    CGContextMoveToPoint(context,200.0,200.0);
    CGContextAddLineToPoint(context,200.0,400.0);
    CGContextStrokePath(context);
}


-(UIImage *)getTheImage
{
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
    NSLog(@"drawImage %@",drawImage);
    return drawImage;
}

Solution

  • You should call this function only when a bitmap-based graphics context is the current graphics context. If the current context is nil or was not created by a call to UIGraphicsBeginImageContext, this function returns nil.

    appearantly your call is not in a context.