Home > Blockchain >  How to crop a image 3:4 ? Swift
How to crop a image 3:4 ? Swift

Time:10-25

I tried to look up the answer on the Internet and did not find it, maybe I typed my query wrong on the Internet.

Can you tell me how to crop a 3:4 photo? I can't find the function to crop it. Please share?

CodePudding user response:

You can use this function to crop your image in any AspectRatio (e.g 3:4). You have to pass your Image and desired AspectRatio as a parameter to the function and it will return you the Cropped Image.

func crop(image: UIImage, to aspectRatio: CGFloat) -> UIImage {

    let originalAspectRatio = image.size.height/image.size.width

    var newImagesize = image.size

    if originalAspectRatio > aspectRatio {
        newImagesize.height = image.size.width * aspectRatio
    } else if originalAspectRatio < aspectRatio {
        newImagesize.width = image.size.height / aspectRatio
    } else {
        return image
    }

    let center = CGPoint(x: image.size.width/2, y: image.size.height/2)
    let origin = CGPoint(x: center.x - newImagesize.width/2, y: center.y - newImagesize.height/2)

    let cgCroppedImage = image.cgImage!.cropping(to: CGRect(origin: origin, size: CGSize(width: newImagesize.width, height: newImagesize.height)))!
    let croppedImage = UIImage(cgImage: cgCroppedImage, scale: image.scale, orientation: image.imageOrientation)

    return croppedImage
}

Usage:

 let croppedImage = crop(image: "ImageName", to: 3/4)

CodePudding user response:

Use the following function. For more details read this.

func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage? 
{    
    let imageViewScale = max(inputImage.size.width / viewWidth,
                             inputImage.size.height / viewHeight)

    // Scale cropRect to handle images larger than shown-on-screen size
    let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
                          y:cropRect.origin.y * imageViewScale,
                          width:cropRect.size.width * imageViewScale,
                          height:cropRect.size.height * imageViewScale)

    // Perform cropping in Core Graphics
    guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
    else {
        return nil
    }

    // Return image to UIImage
    let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
    return croppedImage
}
  • Related