繁体   English   中英

如何在 Swift 中从 CGImage 创建 UIImage?

[英]How do I create a UIImage from a CGImage in Swift?

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

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

我究竟做错了什么?

如果您查看 Xcode6 中的文档,您将看到posterImage()返回一个Unmanaged<CGImage>! (在 Swift 中,在 ObjC 中它返回一个CGImageRef )。 在从文档中进行了一些调查后,我发现了这一点:

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

所以你的解决方案是:

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

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

你有没有尝试过

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

这是一个适用于 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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