我正在迅速获得不受支持的参数组合CGBitmap错误

问题描述 投票:30回答:8

我正在尝试快速创建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
ios swift cgcontext cgbitmapcontext
8个回答
62
投票

以防万一有人遇到相同的问题。下面的代码段终于可以使用了。

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上下文


15
投票

已为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
    }

10
投票

在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

4
投票

建议与Xcode 8.3Xcode 9]兼容的方式,它支持Swift 3Swift 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
    }

4
投票

我在Swift 1.2中使用UInt遇到了一些问题,现在我正在使用Int,并且可以正常工作。此示例显示如何将图像转换为灰度图像。


4
投票

已更新为[[Swift 5


1
投票
在Swift 2.2中:

0
投票
CGBitmapInfo.AlphaInfoMask不是有效的位图信息。
© www.soinside.com 2019 - 2024. All rights reserved.