我正在尝试快速创建CGContext。它可以编译,但在运行时会引发错误。
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
let context:CGContext = CGBitmapContextCreate(nil, 20, 20, 8, 0, colorSpace, CGBitmapInfo.AlphaInfoMask)
CGColorSpaceRelease(colorSpace);
....
错误是:
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
以防万一有人遇到相同的问题。下面的代码段终于可以使用了。
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)
它迅速生成一个32位RGBA上下文
已为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
}
在Swift 2.1中,人们可以正确地访问字段,甚至可以将它们或在一起:
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)
let context = CGBitmapContextCreate(baseAddress, width, height, 8,
bytesPerRow, colorSpace, bitmapInfo.rawValue);
大量的'rawValue'正在进行:)
您甚至不需要将bitmapInfo分离出来,并且可以执行单线操作:
let context = CGBitmapContextCreate(baseAddress, width, height, 8,
bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue
建议与Xcode 8.3和Xcode 9]兼容的方式,它支持Swift 3和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
}
我在Swift 1.2中使用UInt
遇到了一些问题,现在我正在使用Int
,并且可以正常工作。此示例显示如何将图像转换为灰度图像。
已更新为[[Swift 5