kCGImageAlphaNone unresolved identifier in swift

2019-02-18 02:20发布

问题:

I am trying to convert images/textures (for SpriteKit) to grayscale with CoreImage in Swift :

I found this answer : https://stackoverflow.com/a/17218546/836501 which I try to convert to swift for iOS7/8

But kCGImageAlphaNone doesn't exist. Instead I can use CGImageAlphaInfo.None but the function CGBitmapContextCreate() doesn't like it as its last parameter. I am obliged to use the enum CGBitmapInfo but there doesn't seem to be the kCGImageAlphaNone equivalent inside.

This is the full line with the wrong parameter (last one) :

var context = CGBitmapContextCreate(nil, UInt(width), UInt(height), 8, 0, colorSpace, kCGImageAlphaNone)

I just need a way to convert UIImage to grayscale in Swift.

回答1:

You have to create a struct CGBitmapInfo from the CGImageAlphaInfo.None value:

let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.None.rawValue)
var context = CGBitmapContextCreate(nil, UInt(width), UInt(height), 8, 0, colorSpace, bitmapInfo)


回答2:

I believe the original Objective-C code was wrong. The kCGImageAlphaNone enum value was not the appropriate type to be passing, but Objective-C is less type safe (an enum is an enum) so it worked. The raw value of kCGImageAlphaNone is 0, so passing CGBitmapInfo.allZeros or CGBitmapInfo.ByteOrderDefault (both of which have raw values of 0) should give you the same results.