xcode swift如何拆分图像?

时间:2015-10-12 21:51:15

标签: xcode swift split imageview

我正在使用Swift 2.0,我想将图像分成多个部分。我知道这是重复的,但是它们的语法很老,我无法更新。

1 个答案:

答案 0 :(得分:10)

更新: Xcode 8.2.1•Swift 3.0.2

您可以添加此扩展程序以拆分图片:

extension UIImage {
    var topHalf: UIImage? {
        guard let image = cgImage?
            .cropping(to: CGRect(origin: .zero,
                    size: CGSize(width: size.width,
                                 height: size.height / 2 )))
        else { return nil }
        return UIImage(cgImage: image, scale: 1, orientation: imageOrientation)
    }
    var bottomHalf: UIImage? {
        guard let image = cgImage?
            .cropping(to: CGRect(origin: CGPoint(x: 0,
                                                 y: size.height - (size.height/2).rounded()),
                                 size: CGSize(width: size.width,
                                              height: size.height -
                                                      (size.height/2).rounded())))
        else { return nil }
        return UIImage(cgImage: image)
    }
    var leftHalf: UIImage? {
        guard let image = cgImage?
            .cropping(to: CGRect(origin: .zero,
                                 size: CGSize(width: size.width/2,
                                              height: size.height)))
        else { return nil }
        return UIImage(cgImage: image)
    }
    var rightHalf: UIImage? {
        guard let image = cgImage?
            .cropping(to: CGRect(origin: CGPoint(x: size.width - (size.width/2).rounded(), y: 0),
                                 size: CGSize(width: size.width - (size.width/2).rounded(),
                                              height: size.height)))
        else { return nil }
        return UIImage(cgImage: image)
    }
}

游乐场测试:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let imgURL = URL(string: "https://i.stack.imgur.com/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()