在Objective中,我能够使用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)发布于 2016-12-12 14:20:56
我不知道喜欢的文章中的代码会做什么,但是与Swift代码不同的是两件事。
bytesPerRow: width // width * 4 (== bitmapBytesPerRow)space : NULL // CGColorSpaceCreateDeviceRGB()CGBitmapContextCreate没有提到为colorspace提供NULL的任何内容,但是标头文档表示,每个像素的组件数是由指定的,因此CGColorSpaceCreateDeviceRGB()至少不适合于alphaOnly (alphaOnly每个像素应该只有一个组件)。
据我测试,此代码返回非零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)但是,不确定这是否适合你的目的。
发布于 2019-03-15 13:36:00
我当时正在做这件事,也面临着同样的问题。我找到的解决办法是用
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)!并将其传递给上下文。它解决了我的错误(无上下文问题)。
https://stackoverflow.com/questions/41100895
复制相似问题