简体   繁体   中英

Swift UIImage from CALayer crash

I am using PocketSVG framework in order to render SVG images. This framework renders the SVG onto a CAShapeLayer which can then be added to a views sublayer to display the SVG. I would like to generate a UIImage from this CAShapeLayer, however the code to do this does not seem to work in Swift. In objective-c, this is fairly simple, code I have used below

    - (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;
}

I have tested this out in an Objective-c project, and this works fine. So I converted the above code to Swift

 func imageFromLayer (layer : CALayer) -> UIImage
{
    if(UIScreen.mainScreen().respondsToSelector("scale"))
    {
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, UIScreen.mainScreen().scale)
    }
    else
    {
        UIGraphicsBeginImageContext(layer.frame.size)
    }

    layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()
    return outputImage
}

However the app is crashing on this line

layer.renderInContext(UIGraphicsGetCurrentContext()!)

Saying "fatal error: unexpectedly found nil while unwrapping an Optional value"

Does anyone know why this is happening? As a work around, I even tried adding a bridging header file into my Swift project, and added an Objective-c class which contains imageFromLayer method, however when I run this method in my Swift class, I get the following error

<Error>: CGContextSetStyle: invalid context 0x0.

Anyone have any ideas why this is happening in Swift?

Try changing layer.frame.size throughout to layer.bounds.size . Layers don't really have frames, except as a slippery derived notion, so you are ending up with a zero sized graphics context, which is invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM