Sujay U N
Sujay U N

Reputation: 5340

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

Upvotes: 2

Views: 1337

Answers (1)

idz
idz

Reputation: 12988

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

Upvotes: 3

Related Questions