Search code examples
swift3uiimage

Cut image in pieces swift3 / Ambiguous use of init((CGImage: scale: orientation:)


I am trying to following this discussion. The suggested solution was written for Swift 2. I have updated it to Swift 3 and got an error "Ambiguous use of init((CGImage: scale: orientation:)" for the line:

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

Have you any idea how to repair it? Here is the code:

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
}

}


Solution

  • Just wanted to make sure that Rob's comment gets highlighted since that seems to be the correct answer. To add to it, as of Swift 4, method signature stays what Rob has mentioned.

    Rob: "In Swift 3, the first label to that function is now cgImage:, not CGImage:. See init(cgImage:scale:orientation:)."

    For e.g.:

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