georgebp
georgebp

Reputation: 323

CGContext.init for ARGB image returns nil

I'm trying to create a CGContext and fill it with an array of pixels with an ARGB format. I've successfully created the pixel array, but when I try to create the CGContext with CGColorSpaceCreateDeviceRGB and CGImageAlphaInfo.first, it 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!
}

Upvotes: 0

Views: 608

Answers (1)

Pavel Kozlov
Pavel Kozlov

Reputation: 1003

Please refer to the Supported Pixel Formats.

Seems like you use incorrect configuration (CGImageAlphaInfo.first). For 8 bitsPerComponent and RGB color space you have only the following valid alpha options:

  • kCGImageAlphaNoneSkipFirst
  • kCGImageAlphaNoneSkipLast
  • kCGImageAlphaPremultipliedFirst
  • kCGImageAlphaPremultipliedLast

You can also try setting CGBITMAP_CONTEXT_LOG_ERRORS environment variable in your scheme to get more information in runtime.

Upvotes: 2

Related Questions