如何在Swift中从CGImage创建UIImage?

Bil*_*ill 18 core-foundation uiimage cgimage swift

我正在尝试UIImage从该ALAssetsGroup#posterImage方法创建一个.在Objective-C中,我可以简单地调用[UIImage imageWithCGImage:group.posterImage]但在Swift中,UIImage(CGImage: group.posterImage)给我一个编译器错误:

Could not find an overload for 'init' that accepts the supplied arguments
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Fir*_*iro 28

如果你看一下Xcode6中的文档,你会看到posterImage()返回一个Unmanaged<CGImage>!(在Swift中,在ObjC中它返回一个CGImageRef).经过对文档的一些调查后我发现了这个:

从未注释的API接收非托管对象时,应在使用它之前立即将其转换为内存管理对象.

所以你的解决方案是:

UIImage(CGImage: group.posterImage().takeUnretainedValue())
Run Code Online (Sandbox Code Playgroud)


Alb*_*ddy 8

您确定 group.posterImage 不是可选的吗?

你有没有尝试过

var img = UIImage(CGImage: group.posterImage!)
Run Code Online (Sandbox Code Playgroud)