在使用CGBitmapContextCreate的時候,使用kCGImageAlpahPremultipliedLast,卻沒想到報錯,unresolved identifier error for ‘kCGImageAlphaPremultipliedLast’
也就是識別不了kCGImageAlphaPremultipliedLast,沒定義,該枚舉常量在OC裏面使用明明是好的啊。
CGBitmapContextCreate(&pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width*4, imageCS, bitmapInfo: kCGImageAlphaPremultipliedLast)
Swift中該方法的定義最後一個參數類型是UInt32
CGBitmapContextCreate(data: UnsafeMutablePointer<Void>, _ width: Int, _ height: Int, _ bitsPerComponent: Int, _ bytesPerRow: Int, _ space: CGColorSpace?, _ bitmapInfo: UInt32)
在OC中,CGBitmapInfo的定義如下:
typedef CF_OPTIONS(uint32_t, CGBitmapInfo) {
kCGBitmapAlphaInfoMask = 0x1F,
kCGBitmapFloatComponents = (1 << 8),
...
} CF_ENUM_AVAILABLE(10_4, 2_0);
類似的還有CGImageAlphaInfo
typedef CF_ENUM(uint32_t, CGImageAlphaInfo) {
kCGImageAlphaNone, /* For ex, RGB. */
kCGImageAlphaPremultipliedLast, /* For ex, premultiplied RGBA */
kCGImageAlphaPremultipliedFirst, /* For ex, premultiplied ARGB */
...
};
所以我們可以在OC中直接使用kCGImageAlpahPremultipliedLast等枚舉常量。
但是在Swift中,CGBitmapInfo的定義卻有些不同,它是一個Struct。
public struct CGBitmapInfo : OptionSetType {
public init(rawValue: UInt32)
public static var AlphaInfoMask: CGBitmapInfo { get }
public static var FloatComponents: CGBitmapInfo { get }
...
}
而”alpha info” 被分開定義成了一個枚舉。
public enum CGImageAlphaInfo : UInt32 {
case None /* For example, RGB. */
case PremultipliedLast /* For ex, premultiplied RGBA */
case PremultipliedFirst /* For ex, premultiplied ARGB */
...
}
因此, 必須將enum轉換爲UInt32的值來創建CGBitmapInfo。
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(..., bitmapInfo)
下邊一個”完整”的示例來說明兩種語言下的實現方式
OC:
CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
Swift:
let bmpInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue|CGBitmapInfo.ByteOrder32Little.rawValue)
let newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, bmpInfo.rawValue)