首页 > 解决方案 > ARGB 图像的 CGContext.init 返回 nil

问题描述

我正在尝试创建一个 CGContext 并用 ARGB 格式的像素数组填充它。我已经成功创建了像素数组,但是当我尝试使用 CGColorSpaceCreateDeviceRGB 和 CGI​​mageAlphaInfo.first 创建 CGContext 时,它返回 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!
}

标签: iosswiftbitmapcgcontextcgimage

解决方案


请参阅支持的像素格式

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

  • kCGImageAlphaNoneSkipFirst
  • kCGImageAlphaNoneSkipLast
  • kCGImageAlphaPremultipliedFirst
  • kCGImageAlphaPremultipliedLast

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


推荐阅读