问题描述
我有一个来自 UIImage
的 ARKit
。我希望能够以高精度采样该图像的颜色。搜索 UIImage 或 CGImage 的示例颜色会返回如下所示的代码,其中包含四个 UInt8
组件。
我尝试更改每个组件的位,但不知道如何调整 CGContext
的其他参数以使其呈现。
如何指定 CoreGraphics 使用 16 位颜色组件渲染 UIImage? (或者 UInt8 以外的其他东西?)
let result = renderer.image { imageRendererContext in
let context = imageRendererContext.cgContext
context.setStrokeColor(UIColor.clear.cgColor)
let maskWidth = Int(mask.size.width)
let maskHeight = Int(mask.size.height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * maskWidth
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
guard let maskContext = CGContext(data: nil,width: maskWidth,height: maskHeight,bitsPerComponent: bitsPerComponent,bytesPerRow: bytesPerRow,space: colorSpace,bitmapInfo: bitmapInfo),let maskPointer = maskContext.data?.assumingMemoryBound(to: UInt8.self) else {
return
}
maskContext.draw(maskCGImage,in: CGRect(x: 0,y: 0,height: maskHeight))
for x in 0 ..< maskWidth {
for y in 0 ..< maskHeight {
let i = bytesPerRow * Int(y) + bytesPerPixel * Int(x)
let a = CGFloat(maskPointer[i + 3]) / 255.0
let r = (CGFloat(maskPointer[i]) / a) / 255.0
let g = (CGFloat(maskPointer[i + 1]) / a) / 255.0
let b = (CGFloat(maskPointer[i + 2]) / a) / 255.0
}
}
}
解决方法
发现 described in the core graphics guide, 每个组件 16 位及更高仅适用于 MacOS,而不适用于 iOS