CGImage蒙版在宽色域显示器上不起作用

时间:2017-10-18 19:32:56

标签: ios ipad core-graphics

我有一个UIView子类,它渲染了一个应用了蒙版的图像。它适用于所有设备(仅适用于iPad),除了那些具有宽色域显示器(最新的iPad专业版)的设备,其中蒙版呈现完全透明(它看起来像用户看起来不在那里)。相关的init / drawRect代码如下所示:

init(image: UIImage) {
    scratchable = image.cgImage!
    imageWidth = scratchable.width
    imageHeight = scratchable.height

    let colorspace = CGColorSpaceCreateDeviceGray()

    let pixels = CFDataCreateMutable(nil, imageWidth * imageHeight)!

    alphaPixels = CGContext(
        data: CFDataGetMutableBytePtr(pixels),
        width: imageWidth,
        height: imageHeight,
        bitsPerComponent: 8,
        bytesPerRow: imageWidth,
        space: colorspace,
        bitmapInfo: CGImageAlphaInfo.none.rawValue
    )!
    provider = CGDataProvider(data: pixels)!

    alphaPixels.setFillColor(UIColor.black.cgColor)

    let mask = CGImage(
        maskWidth: imageWidth,
        height: imageHeight,
        bitsPerComponent: 8,
        bitsPerPixel: 8,
        bytesPerRow: imageWidth,
        provider: provider,
        decode: nil,
        shouldInterpolate: false
    )!

    scratched = scratchable.masking(mask)!

    super.init(frame: CGRect(x: 0, y: 0, width: imageWidth/2, height: imageHeight/2))

    alphaPixels.fill(imageRect)

    isOpaque = false
}

override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()!
    context.saveGState()
    context.translateBy(x: 0, y: bounds.size.height)
    context.scaleBy(x: 1.0, y: -1.0)
    context.draw(scratched, in: rect)
    context.restoreGState()
}

(对于上下文,pixelsalphaPixels等原因是必要的,因为类中的其他代码会引入上下文以影响掩码。)

任何想法为什么宽色域显示会影响这个,或者可以做些什么来解决它?我认为它可能与颜色空间有关,但是文档明确指出掩码必须使用CGColorSpaceCreateDeviceGray才能正常工作(确实如此)。

以下是展示问题的示例项目:http://d.pr/f/IS4SEF

1 个答案:

答案 0 :(得分:2)

讨论后更新:

问题似乎在于处理CFData。

CFDataCreateMutable(CFAllocatorRef allocator, CFIndex capacity)

capacity参数是" CFData对象可以包含的最大字节数。"我们仍然需要通过附加字节或

来处理length属性
CFDataSetLength(pixels, imageWidth * imageHeight)

原始答案:

请尝试不使用命名颜色,例如UIColor.black。改为从组件中组合颜色。 Core Graphics可能无法正确处理混合色彩空间。