I am trying to create a CGContext in swift. It compiles but throws an error at runtime.
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
let context:CGContext = CGBitmapContextCreate(nil, 20, 20, 8, 0, colorSpace, CGBitmapInfo.AlphaInfoMask)
CGColorSpaceRelease(colorSpace);
....
And the error is:
Error: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 32 bits/pixel; 3-component color space; unrecognized; 96 bytes/row.
fatal error: Can't unwrap Optional.None
Just in case somebody is running into the same problem. The snippet below finally works.
It generates a 32 bit RGBA context in swift
In Swift 2.1 one can access the fields properly, and even OR them together:
Whole lot of 'rawValue' going on :)
You don't even need to separate out the bitmapInfo, and can do a one-liner:
In Swift 2.2:
CGBitmapInfo.AlphaInfoMask is not a valid bitmap info.
Try setting CGBitmapInfo.AlphaLast or CGBitmapInfo.AlphaFirst.
I had some issues in Swift 1.2 using
UInt
, now I'm usingInt
and it's working. This Example shows how to convert an Image to a grayscale image.Updated for Swift 3: