空 CGContext

Empty CGContext

在 Objective-C 中,我能够使用 CGBitmapContextCreate 创建一个空上下文。我试图在 Swift 3 中做同样的事情,但由于某种原因它是零。我错过了什么?

let inImage: UIImage = ...
let width = Int(inImage.size.width)
let height = Int(inImage.size.height)

let bitmapBytesPerRow = width * 4
let bitmapByteCount = bitmapBytesPerRow * height

let pixelData = UnsafeMutablePointer<UInt8>.allocate(capacity: bitmapByteCount)

let context = CGContext(data: pixelData,
                                width: width,
                                height: height,
                                bitsPerComponent: 8,
                                bytesPerRow: bitmapBytesPerRow,
                                space: CGColorSpaceCreateDeviceRGB(),
                                bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)

我不确定喜欢的文章中的代码会做什么,但是有两点与您的 Swift 代码不同。

  • bytesPerRow: width // width * 4 (== bitmapBytesPerRow)
  • space : NULL // CGColorSpaceCreateDeviceRGB()

documentation of CGBitmapContextCreate 没有说明为 colorspace 提供 NULL,但是 header 文档说 每个像素的分量数由 space 指定,因此,至少 CGColorSpaceCreateDeviceRGB() 不适合 alphaOnly(每个像素应该只有 1 个分量)。

据我测试,这段代码 returns non-nil CGContext:

    let bitmapBytesPerRow = width //<-
    let bitmapByteCount = bitmapBytesPerRow * height

    let pixelData = UnsafeMutablePointer<UInt8>.allocate(capacity: bitmapByteCount)

    let context = CGContext(data: pixelData,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: CGColorSpaceCreateDeviceGray(), //<-
                            bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)

但是,不确定这是否适合您的目的。

我正在处理这件事并遇到了同样的问题。 我找到的解决方案是使用

var colorSpace =   CGColorSpace.init(name: CGColorSpace.sRGB)!
  let context = CGContext(data: nil,
                            width: Int(outputSize.width),
                            height: Int(outputSize.height),
                            bitsPerComponent: self.bitsPerComponent,
                            bytesPerRow: bitmapBytesPerRow,
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)

实际上我图像的颜色 space 已编入索引,无法用于创建上下文。 因此,我没有使用图像自己的颜色空间,而是使用

制作了自己的颜色空间
var colorSpace =   CGColorSpace.init(name: CGColorSpace.sRGB)!

并将其传递给上下文。 它解决了我的错误(无上下文问题)。