我有以下代码将 CGImage
转换为 NSData
:
import Foundation
import CoreGraphics
import ImageIO
// ... snip ...
let data = NSMutableData()
if let dest = CGImageDestinationCreateWithData(data, kUTTypePNG, 1, nil), let image = self.backgroundImage {
CGImageDestinationAddImage(dest, image, nil)
if CGImageDestinationFinalize(dest) {
return data as Data
}
}
return nil
代码在 Mac-OS 中编译良好,但 kUTTypePNG
在 iOS 中未定义。常量的实际值是 "public.png"
,显然,用该值替换常量允许 iOS 正确编译代码。
但是避免使用神奇的字符串/数字是我们首先使用常量的原因 - Swift-iOS 中是否有替代常量?
最佳答案
来自 Mobile Core Services Framework在“iOS 技术概述”中:
The Mobile Core Services framework (MobileCoreServices.framework) defines the low-level types used in uniform type identifiers (UTIs).
For more information about the types defined by this framework, see Uniform Type Identifiers Reference.
所以
import MobileCoreServices
制作
public let kUTTypePNG: CFString
以及您的代码可用的其他 UTI 常量。
关于ios - iOS 中的 CGImageDestinationCreateWithData 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38916484/