CGContext.init 对于 ARGB 图像 returns 无

CGContext.init for ARGB image returns nil

我正在尝试创建一个 CGContext 并用 ARGB 格式的像素数组填充它。我已经成功创建了像素数组,但是当我尝试使用 CGColorSpaceCreateDeviceRGB 和 CGImageAlphaInfo.first 创建 CGContext 时,它 returns nil.

func generateBitmapImage8bit() -> CGImage {
    let width = params[0]
    let height = params[1]
    let bitmapBytesPerRow = width * 4

    let context = CGContext(data: nil,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: CGColorSpaceCreateDeviceRGB(), //<-
        bitmapInfo: CGImageAlphaInfo.first.rawValue)

    context!.data!.storeBytes(of: rasterArray, as: [Int].self)

    let image = context!.makeImage()
    return image!
}

请参考Supported Pixel Formats

您似乎使用了不正确的配置 (CGImageAlphaInfo.first)。对于 8 bitsPerComponent 和 RGB 颜色 space,您只有以下有效的 alpha 选项:

  • kCGImageAlphaNoneSkipFirst
  • kCGImageAlphaNoneSkipLast
  • kCGImageAlphaPremultipliedFirst
  • kCGImageAlphaPremultipliedLast

您也可以尝试在方案中设置 CGBITMAP_CONTEXT_LOG_ERRORS 环境变量,以在运行时获取更多信息。