swift 中带有比例的 UIImage init 错误地表示 "Extra Argument"

UIImage init with scale in swift says "Extra Argument" Erroneously

好的。这很古怪。我检查了上面的各种答案,this is the only one that seems to really hit the mark.

然而,似乎没有答案。

我正在使用 Swift 创建一个新的 UIImage,完全像这样(Objective-C 版本):

UIImage *myImage = [[UIImage alloc] initWithCGImage: aCGImageRefAllocatedPreviously scale:aCGFloatScaleCalculatedPreviously orientation:UIImageOrientationUp];

效果很好。但是,当我在 Swift 中尝试 the same exact call 时:

let myImage = UIImage ( CGImage: aCGImageAllocatedPreviously, scale:aCGFloatScaleCalculatedPreviously, orientation:UIImageOrientation.Up )

我收到一个编译器错误,告诉我 "scale" 是一个额外的参数。

这是签名错误时出现的错误。

然而,这并没有错(据我所知)。

我正在做的是通过完全复制 Swift 中的 Objective-C 函数来创建一个教程(我知道,我知道,Swift 是不同的,所以我不应该完全复制,但是,正如 Bill Murray 所说,"Baby Steps").

我想知道我到底是怎么搞砸的。

如果我只用图像调用它(没有比例或方向),它工作正常,但我需要那个比例。

我在 playground 上尝试了这个并且能够编译这个代码:

import UIKit
import AVFoundation

let myImage = UIImage(CGImage: nil,
  scale:0,
  orientation:UIImageOrientation.Up)

此语法也适用:

let newImage = UIImage.init(CGImage: nil,
  scale:0,
  orientation:UIImageOrientation.Up )

好的。我想通了。我是个傻瓜。

我需要在 CGImage 上使用 takeRetainedValue(),像这样:

let myImage = UIImage ( CGImage: aCGImageAllocatedPreviously.takeRetainedValue(),scale:aCGFloatScaleCalculatedPreviously,orientation:UIImageOrientation.Up )

满足签名。