在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
没有说明为NULL
提供colorspace
,但是标题doc说每个像素的组件数量由space
指定,因此,至少CGColorSpaceCreateDeviceRGB()
不适合alphaOnly
(每个像素应该只有1个分量) 。
据我测试,此代码返回非零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)
实际上我的图像的颜色空间是索引,不能用于创建上下文。因此,我没有使用图像自己的colorSpace,而是使用了自己的
var colorSpace = CGColorSpace.init(name: CGColorSpace.sRGB)!
并将其传递给上下文。它解决了我的错误(无上下文问题)。