Cropping center square of UIImage

后端 未结 18 676
日久生厌
日久生厌 2020-12-07 23:09

So here\'s where I\'ve made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn\'t transl

18条回答
  •  渐次进展
    2020-12-07 23:32

    Here is the Swift 5 version of cropping the image according to given size from center.

    extension UIImage {
    
         func imageByCroppingImage(size : CGSize) -> UIImage{
            let refWidth : CGFloat = CGFloat(self.cgImage!.width)
            let refHeight : CGFloat = CGFloat(self.cgImage!.height)
            let x = (refWidth - size.width) / 2
            let y = (refHeight - size.height) / 2
            let cropRect = CGRect(x: x, y: y, width: size.width, height: size.height)
            let imageRef = self.cgImage!.cropping(to: cropRect)
            let cropped : UIImage = UIImage(cgImage: imageRef!, scale: 0, orientation: self.imageOrientation)
            return cropped
        }
        }
    

提交回复
热议问题