Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am getting unsupported parameter combination CGBitmap error with swift

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
like image 643
loopmasta Avatar asked Jun 08 '14 18:06

loopmasta


4 Answers

Just in case somebody is running into the same problem. The snippet below finally works.

let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(nil, UInt(rect.size.width), UInt(rect.size.height), 8, 0, colorSpace, bitmapInfo)

It generates a 32 bit RGBA context in swift

like image 137
loopmasta Avatar answered Nov 04 '22 02:11

loopmasta


Updated for Swift 3:

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
    guard let context = CGContext.init(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: Int(bitsPerComponent), bytesPerRow: Int(bytesPerRow), space: colorSpace, bitmapInfo: UInt32(bitmapInfo.rawValue)) else {
        // cannot create context - handle error
    }
like image 18
Echelon Avatar answered Nov 04 '22 00:11

Echelon


In Swift 2.1 one can access the fields properly, and even OR them together:

let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)

let context = CGBitmapContextCreate(baseAddress, width, height, 8,
                bytesPerRow, colorSpace, bitmapInfo.rawValue);

Whole lot of 'rawValue' going on :)

You don't even need to separate out the bitmapInfo, and can do a one-liner:

let context = CGBitmapContextCreate(baseAddress, width, height, 8,
                bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue
like image 11
Graham Perks Avatar answered Nov 04 '22 01:11

Graham Perks


Updated for Swift 5:

 let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
 let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
 let context = CGContext(data: nil, width: UInt(rect.size.width), height: UInt(rect.size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

where rect has height and width

like image 6
Jawad Ali Avatar answered Nov 04 '22 02:11

Jawad Ali