user4812000
user4812000

Reputation: 1053

xcode swift how do I split an image?

I am working with Swift 2.0 and I would like to split an image into multiple pieces. I know this is a repeat, but they syntax is old and I am having trouble update.

Upvotes: 4

Views: 5067

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236420

update: Xcode 8.2.1 • Swift 3.0.2

You can add this extension to split your images:

extension UIImage {
    var topHalf: UIImage? {
        cgImage?.cropping(
            to: CGRect(
                origin: .zero,
                size: CGSize(width: size.width, height: size.height / 2)
            )
        )?.image
    }
    var bottomHalf: UIImage? {
        cgImage?.cropping(
            to: CGRect(
                origin: CGPoint(x: .zero, y: size.height - (size.height/2).rounded()),
                size: CGSize(width: size.width, height: size.height - (size.height/2).rounded())
            )
        )?.image
    }
    var leftHalf: UIImage? {
        cgImage?.cropping(
            to: CGRect(
                origin: .zero,
                size: CGSize(width: size.width/2, height: size.height)
            )
        )?.image
    }
    var rightHalf: UIImage? {
        cgImage?.cropping(
            to: CGRect(
                origin: CGPoint(x: size.width - (size.width/2).rounded(), y: .zero),
                size: CGSize(width: size.width - (size.width/2).rounded(), height: size.height)
            )
        )?.image
    }
}

extension CGImage {
    var image: UIImage { .init(cgImage: self) }
}

Playground testing:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let imgURL = URL(string: "https://i.sstatic.net/Xs4RX.jpg")!
URLSession.shared.dataTask(with: imgURL) { data, response, error in
    guard
        let data = data, let image = UIImage(data: data)
    else { return }
    
    let topHalf = image.topHalf
    let bottomHalf = image.bottomHalf
    
    let topLeft = topHalf?.leftHalf
    let topRight = topHalf?.rightHalf
    let bottomLeft = bottomHalf?.leftHalf
    let bottomRight = bottomHalf?.rightHalf
}.resume()

Upvotes: 17

Related Questions