Cropping image with Swift and put it on center position

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

    I came up with a code that will give a desired cropped aspect ratio, regardless of original video frame size (adapted from @Cole's answer):

    func cropImage(uncroppedImage: UIImage, cropWidth: CGFloat, cropHeight: CGFloat) -> UIImage {
    
            let contextImage: UIImage = UIImage(cgImage: uncroppedImage.cgImage!)
    
            let contextSize: CGSize = contextImage.size
            var cropX: CGFloat = 0.0
            var cropY: CGFloat = 0.0
            var cropRatio: CGFloat = CGFloat(cropWidth/cropHeight)
            var originalRatio: CGFloat = contextSize.width/contextSize.height
            var scaledCropHeight: CGFloat = 0.0
            var scaledCropWidth: CGFloat = 0.0
    
            // See what size is longer and set crop rect parameters
            if originalRatio > cropRatio {
    
                scaledCropHeight = contextSize.height
                scaledCropWidth = (contextSize.height/cropHeight) * cropWidth
                cropX = (contextSize.width - scaledCropWidth) / 2
                cropY = 0
    
            } else {
                scaledCropWidth = contextSize.width
                scaledCropHeight = (contextSize.width/cropWidth) * cropHeight
                cropY = (contextSize.height / scaledCropHeight) / 2
                cropX = 0
            }
    
            let rect: CGRect = CGRect(x: cropX, y: cropY, width: scaledCropWidth, height: scaledCropHeight)
    
            // 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 croppedImage: UIImage = UIImage(cgImage: imageRef, scale: uncroppedImage.scale, orientation: uncroppedImage.imageOrientation)
    
            return croppedImage
        }
    

    Hope it helps!

提交回复
热议问题