How do I create a UIImage from a CGImage in Swift? How do I create a UIImage from a CGImage in Swift? ios ios

How do I create a UIImage from a CGImage in Swift?


If you look at the docs in Xcode6 you will see that posterImage() returns a Unmanaged<CGImage>! (in Swift, in ObjC it returns a CGImageRef). After some investigation from the docs I found this:

When you receive an unmanaged object from an unannotated API, you should immediately convert it to a memory managed object before you work with it.

So your solution would be:

UIImage(CGImage: group.posterImage().takeUnretainedValue())


Are you sure group.posterImage is not an optional?

have you tried

var img = UIImage(CGImage: group.posterImage!)


Here's an example that should work for you with Xcode 8.3:

    let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 1920, height: 1080))    let cgImage = CIContext().createCGImage(CIImage(color: .black()), from: frame)!    let uiImage = UIImage(cgImage: cgImage)