Cropping center square of UIImage

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

    Based on the checked answer by Elmundo and its swift version by Imbrue, here is the same solution that automatically calculates the size of the image's center (taking orientation into account), and with error consideration:

    func cropImageToSquare(image: UIImage) -> UIImage? {
        var imageHeight = image.size.height
        var imageWidth = image.size.width
    
        if imageHeight > imageWidth {
            imageHeight = imageWidth
        }
        else {
            imageWidth = imageHeight
        }
    
        let size = CGSize(width: imageWidth, height: imageHeight)
    
        let refWidth : CGFloat = CGFloat(CGImageGetWidth(image.CGImage))
        let refHeight : CGFloat = CGFloat(CGImageGetHeight(image.CGImage))
    
        let x = (refWidth - size.width) / 2
        let y = (refHeight - size.height) / 2
    
        let cropRect = CGRectMake(x, y, size.height, size.width)
        if let imageRef = CGImageCreateWithImageInRect(image.CGImage, cropRect) {
            return UIImage(CGImage: imageRef, scale: 0, orientation: image.imageOrientation)
        }
    
       return nil
    }
    

    Swift 3 version

    func cropImageToSquare(image: UIImage) -> UIImage? {
        var imageHeight = image.size.height
        var imageWidth = image.size.width
    
        if imageHeight > imageWidth {
            imageHeight = imageWidth
        }
        else {
            imageWidth = imageHeight
        }
    
        let size = CGSize(width: imageWidth, height: imageHeight)
    
        let refWidth : CGFloat = CGFloat(image.cgImage!.width)
        let refHeight : CGFloat = CGFloat(image.cgImage!.height)
    
        let x = (refWidth - size.width) / 2
        let y = (refHeight - size.height) / 2
    
        let cropRect = CGRect(x: x, y: y, width: size.height, height: size.width)
        if let imageRef = image.cgImage!.cropping(to: cropRect) {
            return UIImage(cgImage: imageRef, scale: 0, orientation: image.imageOrientation)
        }
    
        return nil
    }
    

提交回复
热议问题