Sujay U N Sujay U N - 1 year ago 98
iOS Question

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

idz idz
Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download