swift - 使用任何 RGB 颜色空间时无法获得有效的 CGContext?

标签 swift xcode macos

我正在尝试创建一个 CGContext,我可以在其中绘制图像以检索原始像素数据以供以后处理。我正在使用取决于我正在处理的图像的颜色空间创建 CGContext。这在我使用灰度或 CMYK 色彩空间时工作正常,但在使用任何 RGB 色彩空间时我无法获得有效的 CGContext。下面的片段说明了我看到的行为(使用 Swift 4、XCode 10.1)。我必须遗漏一些明显的东西,但对于我的生活我找不到它。任何帮助将不胜感激!

//let colorSpace3:CGColorSpace = CGColorSpaceCreateDeviceGray() // get good context
//let colorSpace3:CGColorSpace = CGColorSpaceCreateDeviceCMYK() // get good context
//let colorSpace3: CGColorSpace = CGColorSpace(name: CGColorSpace.linearGray)! // get good context
//let colorSpace3: CGColorSpace = CGColorSpace(name: CGColorSpace.genericCMYK)! // get good context
//let colorSpace3:CGColorSpace = CGColorSpaceCreateDeviceRGB() //context3 is nil
//let colorSpace3: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB)! //context3 is nil
//let colorSpace3: CGColorSpace = CGColorSpace(name: CGColorSpace.linearSRGB)! // context3 is nil
let colorSpace3: CGColorSpace = CGColorSpace(name: CGColorSpace.adobeRGB1998)! // context3 is nil

let bmpinfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue) // bmpinfo different settings doesn't change behavior

let context3 = CGContext(data: nil, width: 256, height: 256, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace3, bitmapInfo: bmpinfo.rawValue)

print(context3) // prints nil whenever colorSpace3 is an RGB space??

最佳答案

您应该在控制台中看到 CGBitmapContextCreate: unsupported parameter combination。只是改变

let bmpinfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)

let bmpinfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)

你应该可以开始了。示例:

let colorSpace3: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
let bmpinfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context3 = CGContext(data: nil, width: 256, height: 256, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace3, bitmapInfo: bmpinfo.rawValue)!
print(context3)

打印:

<CGContext 0x600000165580> (kCGContextTypeBitmap)
    <<CGColorSpace 0x60000022a9c0> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1)>
        width = 256, height = 256, bpc = 8, bpp = 32, row bytes = 1024 
        kCGImageAlphaPremultipliedLast | 0 (default byte order) 

顺便说一句,你的小转换舞蹈是不必要的。您只需将 bmpInfo 设置为 CGImageAlphaInfo.premultipliedLast.rawValue 并将其作为 bitmapInfo 参数直接传递给函数。如果您还要将字节顺序信息与 alpha 信息组合在一起,则只需要进行转换。

关于swift - 使用任何 RGB 颜色空间时无法获得有效的 CGContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54974385/

相关文章:

ios - Firestore 查询在创建新文档时未收到更新

iphone - 如何根据行内容制作可变的表格高度大小?

ios - 扩展项目模板未出现在 Xcode 6 中

iphone - 应用内购买支付部分的 EXC_BAD_ACCESS

macos - 使用 PackageMaker 在安装时运行脚本

ios - 复杂布局的动态 CollectionView 标题单元格大小调整

swift - 自定义类 SpriteKit

swift - AudioKit:从 AKOperationGenerator 淡入

python - BSD/OS X 上的网络掩码/IP 地址查找

objective-c - 核心数据是否在后台进行自己的类型转换?