Cropping image with Swift and put it on center position

后端 未结 14 1154
心在旅途
心在旅途 2020-12-01 00:32

In Swift programming , how do you crop an image and put it on the center afterwards?

This is what I\'ve got so far ... I\'ve successfully crop the image but I want t

14条回答
  •  [愿得一人]
    2020-12-01 01:31

    Accepted answer did not work for me, so I tried wrote my own. Here is an effect of my work:

    import UIKit
    
    extension UIImage {
    
        func cropedToRatio(ratio: CGFloat) -> UIImage? {
            let newImageWidth = size.height * ratio
    
            let cropRect = CGRect(x: ((size.width - newImageWidth) / 2.0) * scale,
                                  y: 0.0,
                                  width: newImageWidth * scale,
                                  height: size.height * scale)
    
            guard let cgImage = cgImage else {
                return nil
            }
            guard let newCgImage = cgImage.cropping(to: cropRect) else {
                return nil
            }
    
            return UIImage(cgImage: newCgImage, scale: scale, orientation: imageOrientation)
        }
    }
    

    This function crop image to given ratio. It keeps image scale. Cropped image is always center of original image.

提交回复
热议问题