在使用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)