本文介绍了空CGContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我可以使用 CGBitmapContextCreate 创建一个空上下文.我正试图在Swift 3中做到这一点,但是由于某种原因,它没有任何意义.我想念什么?

In Objective-C I was able to use CGBitmapContextCreate to create an empty context. I am trying to to the same in Swift 3, but for some reason it is nil. What am I missing?

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代码有两点不同.

I'm not sure what the code in the liked article would do, but two things are different with your Swift code.

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

CGBitmapContextCreate 文档没有说关于为 colorspace 提供 NULL 的任何操作,但标头文档显示每个像素的分量数由 space ,因此,至少 CGColorSpaceCreateDeviceRGB()不适合 alphaOnly (每个像素只能包含1个分量).

The documentation of CGBitmapContextCreate does not say anything about supplying NULL for colorspace, but the header doc says The number of components for each pixel is specified by space, so, at least, CGColorSpaceCreateDeviceRGB() is not appropriate for alphaOnly (which should have only 1 component per pixel).

据我测试,此代码返回非nil CGContext :

As far as I tested, this code 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)

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

But, not sure if this works for your purpose or not.

这篇关于空CGContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!