切片图片swift3 /不明确使用init((CGImage:scale:orientation :)

时间:2017-06-13 03:34:10

标签: swift3 uiimage

我正在尝试关注this discussion。建议的解决方案是为Swift 2编写的。我已将其更新为Swift 3并出现错误"模糊地使用init((CGImage:scale:orientation :)和#34;用于该行:

images.append(UIImage(CGImage: tileCgImage, scale: image.scale, orientation: image.imageOrientation))

你知道如何修理吗?这是代码:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func slice(image: UIImage, into howMany: Int) -> [UIImage] {
    let width: CGFloat
    let height: CGFloat

    switch image.imageOrientation {
    case .left, .leftMirrored, .right, .rightMirrored:
        width = image.size.height
        height = image.size.width
    default:
        width = image.size.width
        height = image.size.height
    }

    let tileWidth = Int(width / CGFloat(howMany))
    let tileHeight = Int(height / CGFloat(howMany))

    let scale = Int(image.scale)
    var images = [UIImage]()
    let cgImage = image.cgImage!

    var adjustedHeight = tileHeight

    var y = 0
    for row in 0 ..< howMany {
        if row == (howMany - 1) {
            adjustedHeight = Int(height) - y
        }
        var adjustedWidth = tileWidth
        var x = 0
        for column in 0 ..< howMany {
            if column == (howMany - 1) {
                adjustedWidth = Int(width) - x
            }
            let origin = CGPoint(x: x * scale, y: y * scale)
            let size = CGSize(width: adjustedWidth * scale, height: adjustedHeight * scale)
            let tileCgImage = cgImage.cropping(to: CGRect(origin: origin, size: size))!
            images.append(UIImage(CGImage: tileCgImage, scale: image.scale, orientation: image.imageOrientation))
            x += tileWidth
        }
        y += tileHeight
    }
    return images
}

}

2 个答案:

答案 0 :(得分:0)

只想确保Rob的评论突出显示,因为这似乎是正确的答案。另外,从Swift 4开始,方法签名保持了Rob所提到的。

Rob: “在Swift 3中,该函数的第一个标签现在是cgImage :,而不是CGImage:。请参阅init(cgImage:scale:orientation :)。”

例如:

let resultUIImg = UIImage(cgImage: someCGImg!, scale: origUIImg.scale, orientation: origUIImg.imageOrientation)

答案 1 :(得分:-1)

Swift 3

你可以这样使用:

let image:UIImag = UIImage( cgImage: cgImage )