Search code examples
iosswiftuiviewuiimagecalayer

Swift Get UIImage from layers of UIView


I have CAShapeLayers in my UIView and I want UIImage from the view.
So I am trying thru below function but getting an error at
UIGraphicsGetCurrentContext()

extension UIView
{
    func getImgFromVyuFnc() -> UIImage
    {
        UIGraphicsBeginImageContext(self.frame.size)

        self.layer.renderInContext(UIGraphicsGetCurrentContext())
        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return image!
    }
}

fatal error: unexpectedly found nil while unwrapping an Optional value 2017-08-17 04:17:47.230474 PicPac[1095:488887] fatal error: unexpectedly found nil while unwrapping an Optional value


Solution

  • If the size passed to UIGraphicsBeginImageContext(_) is zero in either or both dimension(s) then UIGraphicsGetCurrentContext() returns nil and so will UIGraphicsGetImageFromCurrentImageContext().