Cropping center square of UIImage

后端 未结 18 659
日久生厌
日久生厌 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:29

    Solution based on Swift 2 extension. Improvised from @Geoffrey and @Nirav Dangi. Note that we set newCropWidth and newCropHeight to image's width or height when they are lesser than the given width or height.

    extension UIImage {
        func imageByCroppingImage(size: CGSize) -> UIImage {
            let newCropWidth, newCropHeight : CGFloat;
    
            if(self.size.width < self.size.height) {
                if (self.size.width < size.width) {
                    newCropWidth = self.size.width;
                }
                else {
                    newCropWidth = size.width;
                }
                newCropHeight = (newCropWidth * size.height)/size.width;
            } else {
                if (self.size.height < size.height) {
                    newCropHeight = self.size.height;
                }
                else {
                    newCropHeight = size.height;
                }
                newCropWidth = (newCropHeight * size.width)/size.height;
            }
    
            let x = self.size.width / 2 - newCropWidth / 2;
            let y = self.size.height / 2 - newCropHeight / 2;
    
            let cropRect = CGRectMake(x, y, newCropWidth, newCropHeight);
            let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect);
    
            let croppedImage : UIImage = UIImage(CGImage: imageRef!, scale: 0, orientation: self.imageOrientation);
    
            return croppedImage;
        }
    }
    

提交回复
热议问题