CGBitmapContextCreate error with swift

2019-01-23 02:06发布

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

7条回答
爷的心禁止访问
2楼-- · 2019-01-23 02:30

Suggested way compatible with both Xcode 8.3 and Xcode 9 which supports Swift 3 and Swift 4

let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let bitmapContext = CGContext(data: nil, 
                                    width: Int(size.width),
                                    height: Int(size.height),
                                    bitsPerComponent: Int(bitsPerComponent),
                                    bytesPerRow: Int(bytesPerRow),
                                    space: colorSpace,
                                    bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
                                  return nil
    }
查看更多
登录 后发表回答