问题 使用CGBitmapInfo和CGImageAlphaInfo进行按位操作


我在执行按位操作时遇到问题 CGImageAlphaInfo 和 CGBitmapInfo 在斯威夫特。

特别是,我不知道如何移植这个Objective-C代码:

bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaNoneSkipFirst;

以下简单的Swift端口产生了一些有点神秘的编译器错误 'CGBitmapInfo' is not identical to 'Bool' 在最后一行:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGImageAlphaInfo.NoneSkipFirst

看一下我注意到的源代码 CGBitmapInfo 被宣布为 RawOptionSetType 而 CGImageAlphaInfo 不是。也许这与它有关?

关于按位运算符的官方文档没有涵盖枚举,这没有任何帮助。


8095
2017-09-10 19:19


起源



答案:


你有正确的等效Swift代码:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)

这有点奇怪,因为 CGImageAlphaInfo 实际上并不是一个位掩码 - 它只是一个UInt32 enum (或带有类型的CF_ENUM / NS_ENUM uint32_t,用C语言表示,其值为0到7。

实际发生的是你的第一行清除了前五位 bitmapInfo, 哪一个  一个位掩码(又名 RawOptionSetType 在斯威夫特),因为 CGBitmapInfo.AlphaInfoMask 是31,或0b11111。然后你的第二行坚持原始价值 CGImageAlphaInfo 枚举到那些清除的位。

我还没有看到其他地方的枚举和位掩码,如果这解释了为什么没有真正的文档。以来 CGImageAlphaInfo 是一个枚举,它的价值是相互排斥的。这没有任何意义:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)

10
2017-09-10 19:49



不再适用于Xcode 6.1 - wfbarksdale
@wbarksdale谢谢,用新语法更新。 - Nate Cook
这在swift 2.0中再次改变,现在使用OptionSetTypeProtocol。现在使用 var bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: ~CGBitmapInfo.AlphaInfoMask.rawValue | CGImageAlphaInfo.NoneSkipFirst.rawValue) - JackPearse


答案:


你有正确的等效Swift代码:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)

这有点奇怪,因为 CGImageAlphaInfo 实际上并不是一个位掩码 - 它只是一个UInt32 enum (或带有类型的CF_ENUM / NS_ENUM uint32_t,用C语言表示,其值为0到7。

实际发生的是你的第一行清除了前五位 bitmapInfo, 哪一个  一个位掩码(又名 RawOptionSetType 在斯威夫特),因为 CGBitmapInfo.AlphaInfoMask 是31,或0b11111。然后你的第二行坚持原始价值 CGImageAlphaInfo 枚举到那些清除的位。

我还没有看到其他地方的枚举和位掩码,如果这解释了为什么没有真正的文档。以来 CGImageAlphaInfo 是一个枚举,它的价值是相互排斥的。这没有任何意义:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)

10
2017-09-10 19:49



不再适用于Xcode 6.1 - wfbarksdale
@wbarksdale谢谢,用新语法更新。 - Nate Cook
这在swift 2.0中再次改变,现在使用OptionSetTypeProtocol。现在使用 var bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: ~CGBitmapInfo.AlphaInfoMask.rawValue | CGImageAlphaInfo.NoneSkipFirst.rawValue) - JackPearse


从Swift 3,Xcode 8 Beta 5开始,语法(如JackPearse指出,它符合OptionSetType协议)再次改变,我们不再需要 ~CGBitmapInfo.AlphaInfoMask.rawValue相反,我们只是使用

let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue)

您可以通过添加其他位图信息设置 | 运算符,例如

let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.first.rawValue)

5
2017-08-23 02:56





事实证明 CGImageAlphaInfo 值需要转换为 CGBitmapInfo 为了执行按位运算。这可以这样做:

bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)

1
2017-09-10 19:23