2014-09-10 35 views
9

我在Swift中使用CGImageAlphaInfoCGBitmapInfo執行按位運算時遇到問題。使用CGBitmapInfo和CGImageAlphaInfo按位運算

特別是,我不知道如何來港這個Objective-C代碼:

bitmapInfo &= ~kCGBitmapAlphaInfoMask; 
bitmapInfo |= kCGImageAlphaNoneSkipFirst; 

下面簡單雨燕端口產生略帶神祕的編譯器錯誤'CGBitmapInfo' is not identical to 'Bool'最後一行:

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

看着源代碼,我注意到CGBitmapInfo被聲明爲RawOptionSetTypeCGImageAlphaInfo不是。也許這跟它有關係?

這對位運算符的官方文檔不包括枚舉沒有幫助。

回答

10

您有權相當於斯威夫特代碼:

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

這是一個有些奇怪,因爲CGImageAlphaInfo實際上不是一個位掩碼 - 它只是一個UInt32的enum(或一個CF_ENUM/NS_ENUM與uint32_t型,在C的說法),與0值至7

什麼是實際發生的是,你的第一線清除的bitmapInfo的前五位,其中位掩碼(Swift中又名爲RawOptionSetType),因爲CGBitmapInfo.AlphaInfoMask是31或0b11111。然後你的第二行將CGImageAlphaInfo枚舉的原始值粘到那些被清除的位上。

我還沒有看到枚舉和位掩碼像這樣在其他任何地方結合,如果這解釋了爲什麼沒有真正的文檔。由於CGImageAlphaInfo是一個枚舉,它的值是互斥的。這沒有任何意義:

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

不再適用於Xcode 6.1 – wbarksdale 2014-10-21 15:48:46

+0

@wbarksdale謝謝,更新了新的語法。 – 2014-10-21 15:54:16

+4

這在swift 2.0中改變了,現在使用OptionSetTypeProtocol。現在使用'var bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue:〜CGBitmapInfo.AlphaInfoMask.rawValue | CGImageAlphaInfo.NoneSkipFirst.rawValue)' – JackPearse 2015-08-20 13:18:36

1

原來,CGImageAlphaInfo值需要轉換爲CGBitmapInfo才能執行按位操作。這是可以做到這樣的:

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

隨着斯威夫特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)