12

我正在将 Apple 的UIImageEffects示例代码从 Objective-C 重写为 Swift,我对以下行有疑问:

vImage_CGImageFormat format = {
    .bitsPerComponent = 8,
    .bitsPerPixel = 32,
    .colorSpace = NULL,
    .bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little,
    .version = 0,
    .decode = NULL,
    .renderingIntent = kCGRenderingIntentDefault
};

这是我在 Swift 中的版本:

let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue)
let format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: bitmapInfo, version: 0, decode: nil, renderingIntent: .RenderingIntentDefault)

这是bitmapInfo在 Swift 中创建的最简单的方法吗?

4

2 回答 2

12

你可以让它更简单一点:

let bimapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
    .union(.ByteOrder32Little)

不幸的是,您无法摆脱CGImageAlphaInfoCGBitmapInfo. 这只是当前 API 的一个弱点。但是一旦你拥有它,你就可以.union将它与其他值结合起来。并且一旦已知枚举类型,您就不必一直重复它。

我很奇怪这里没有可用的操作员。我为此打开了一个雷达,并包含了一个|实现。http://www.openradar.me/23516367

public func |<T: SetAlgebraType>(lhs: T, rhs: T) -> T {
    return lhs.union(rhs)
}

@warn_unused_result
public func |=<T : SetAlgebraType>(inout lhs: T, rhs: T) {
    lhs.unionInPlace(rhs)
}

let bimapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
    | .ByteOrder32Little
于 2015-11-12T14:57:28.027 回答
5

不管你做什么,现在都不漂亮,但我认为最干净的风格(从 Swift 4 开始)是使用类似的东西:

let bitmapInfo: CGBitmapInfo = [
      .byteOrder32Little,
      .floatComponents,
      CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)]

(或使用类似的内联内容。)这至少保留了信息的基本选项集。

于 2017-07-08T23:17:16.693 回答