Swift Get UIImage from layers of UIView

Question

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


Show source
| swift   | ios   | uiview   | uiimage   | calayer   2017-08-17 00:08 1 Answers

Answers to Swift Get UIImage from layers of UIView ( 1 )

  1. 2017-08-17 01:08

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

Leave a reply to - Swift Get UIImage from layers of UIView

◀ Go back