0

I am trying to convert a CALayer to an UIImage with code from this post. Copied here. But when I use it I got tons of error. At first I put it in a NSObject class where I use to store a model. But then I read in the post I am suppose to put it in a controller, view or category of CALayer. I tried putting it in a controller or CALayer and it still doesn't work.

- (UIImage *)imageFromLayer:(CALayer *)layer
{

    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions([layer frame].size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext([layer frame].size);

    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return outputImage;
}

ERROR:

<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
<Error>: CGContextSetLineWidth: invalid context 0x0
<Error>: CGContextMoveToPoint: invalid context 0x0
<Error>: CGContextAddArc: invalid context 0x0
<Error>: CGContextAddArc: invalid context 0x0
<Error>: CGContextAddArc: invalid context 0x0
<Error>: CGContextAddArc: invalid context 0x0
<Error>: CGContextClosePath: invalid context 0x0
<Error>: CGContextDrawPath: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0
<Error>: CGContextSetBaseCTM: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0
<Error>: CGContextEndTransparencyLayer: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0
<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextSetAlpha: invalid context 0x0
4

1 回答 1

4

Check if your layer parameter is nil. Usually a context cannot be created if the size has either width = 0 or height = 0 (or both).

于 2013-08-08T05:15:43.287 回答