Cropping image with Swift and put it on center position

后端 未结 14 1105
心在旅途
心在旅途 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:32

    Working Swift 3 example

    extension UIImage {
    
        func crop(to:CGSize) -> UIImage {
            guard let cgimage = self.cgImage else { return self }
    
            let contextImage: UIImage = UIImage(cgImage: cgimage)
    
            let contextSize: CGSize = contextImage.size
    
            //Set to square
            var posX: CGFloat = 0.0
            var posY: CGFloat = 0.0
            let cropAspect: CGFloat = to.width / to.height
    
            var cropWidth: CGFloat = to.width
            var cropHeight: CGFloat = to.height
    
            if to.width > to.height { //Landscape
                cropWidth = contextSize.width
                cropHeight = contextSize.width / cropAspect
                posY = (contextSize.height - cropHeight) / 2
            } else if to.width < to.height { //Portrait
                cropHeight = contextSize.height
                cropWidth = contextSize.height * cropAspect
                posX = (contextSize.width - cropWidth) / 2
            } else { //Square
                if contextSize.width >= contextSize.height { //Square on landscape (or square)
                    cropHeight = contextSize.height
                    cropWidth = contextSize.height * cropAspect
                    posX = (contextSize.width - cropWidth) / 2
                }else{ //Square on portrait
                    cropWidth = contextSize.width
                    cropHeight = contextSize.width / cropAspect
                    posY = (contextSize.height - cropHeight) / 2
                }
            }
    
            let rect: CGRect = CGRect(x: posX, y: posY, width: cropWidth, height: cropHeight)
            // Create bitmap image from context using the rect
            let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
    
            // Create a new image based on the imageRef and rotate back to the original orientation
            let cropped: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)
    
            UIGraphicsBeginImageContextWithOptions(to, true, self.scale)
            cropped.draw(in: CGRect(x: 0, y: 0, width: to.width, height: to.height))
            let resized = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return resized!
        }
    }
    
    0 讨论(0)
  • 2020-12-01 01:33

    You can just crop using:

    let croppedImage = yourImage.cgImage.cropping(to:rect)
    
    0 讨论(0)
提交回复
热议问题