我收到“kCGImageAlphaPremultipliedLast”的 Unresolved 标识符错误。 Swift无法找到它。在Swift中可用吗?

var gc = CGBitmapContextCreate(&pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width*4, imageCS, bitmapInfo: kCGImageAlphaPremultipliedLast);

最佳答案

CGBitmapContextCreate()的最后一个参数定义为struct

struct CGBitmapInfo : RawOptionSetType {
    init(_ rawValue: UInt32)
    init(rawValue: UInt32)

    static var AlphaInfoMask: CGBitmapInfo { get }
    static var FloatComponents: CGBitmapInfo { get }
    // ...
}

其中可能的“alpha info”位分别定义为枚举:
enum CGImageAlphaInfo : UInt32 {
    case None /* For example, RGB. */
    case PremultipliedLast /* For example, premultiplied RGBA */
    case PremultipliedFirst /* For example, premultiplied ARGB */
    // ...
}

因此,您必须将枚举转换为其基础的UInt32
然后从中创建一个CGBitmapInfo:
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let gc = CGBitmapContextCreate(..., bitmapInfo)

Swift 2的更新: CGBitmapInfo定义已更改为
public struct CGBitmapInfo : OptionSetType

可以用初始化
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)

10-08 19:26