简体   繁体   中英

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

I'm trying to create a UIImage from the ALAssetsGroup#posterImage method. In Objective-C, I could simply call [UIImage imageWithCGImage:group.posterImage] but in Swift, UIImage(CGImage: group.posterImage) gives me a compiler error:

Could not find an overload for 'init' that accepts the supplied arguments

What am I doing wrong?

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)

将 init 与 CGIImage 一起使用:

UIImage.init(CGImage: group.posterImage, scale: self.scale, orientation: .UpMirrored)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM