簡體   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