Crop UIImage to center square

后端 未结 1 368
慢半拍i
慢半拍i 2020-12-11 09:04

I get images that are in 1920x1080 resolution. I am attempting to crop them to the center square area (ie 1080x1080 square in the center). The resolution may change in the f

相关标签:
1条回答
  • 2020-12-11 09:15

    You can use the same approach I used in this answer without the line UIBezierPath(ovalIn: breadthRect).addClip()


    extension UIImage {
        var isPortrait:  Bool    { size.height > size.width }
        var isLandscape: Bool    { size.width > size.height }
        var breadth:     CGFloat { min(size.width, size.height) }
        var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
        func squared(isOpaque: Bool = false) -> UIImage? {
            guard let cgImage = cgImage?
                .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                                  y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                    size: breadthSize)) else { return nil }
            let format = imageRendererFormat
            format.opaque = isOpaque
            return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
                UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation)
                .draw(in: .init(origin: .zero, size: breadthSize))
            }
        }
    }
    

    let imageURL = URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!
    let image = UIImage(data: try! Data(contentsOf: imageURL))!
    
    let squared = image.squared()
    
    0 讨论(0)
提交回复
热议问题