11

I am getting a unresolved identifier error for 'kCGImageAlphaPremultipliedLast'. Swift can't find it. Is this available in Swift?

var gc = CGBitmapContextCreate(&pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width*4, imageCS, bitmapInfo: kCGImageAlphaPremultipliedLast);
genpfault
  • 51,148
  • 11
  • 85
  • 139
NJGUY
  • 2,045
  • 3
  • 23
  • 43

2 Answers2

23

The last parameter of CGBitmapContextCreate() is defined as a struct

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

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

where the possible "alpha info" bits are defined separately as an enumeration:

enum CGImageAlphaInfo : UInt32 {
    case None /* For example, RGB. */
    case PremultipliedLast /* For example, premultiplied RGBA */
    case PremultipliedFirst /* For example, premultiplied ARGB */
    // ...
}

Therefore you have have to convert the enum to its underlying UInt32 value and then create a CGBitmapInfo from it:

let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let gc = CGBitmapContextCreate(..., bitmapInfo)

Update for Swift 2: The CGBitmapInfo definition changed to

public struct CGBitmapInfo : OptionSetType

and it can be initialized with

let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

The Apple documentation suggests CGImageAlphaInfo.PremultipliedLast.

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGImage/index.html#//apple_ref/c/tdef/CGImageAlphaInfo

Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51