FS.O6 FS.O6 - 2 years ago 201
Swift Question

Resize UIImage to 100% and crop

I have a landscape

that I want to crop to 900x900 size.

I don't want it to be stretched - I want it to scale it to 100% - the image will be scaled to fit 900x900, and the part of the image that is out of bounds will be cropped.

I've tried this code:

UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.main.scale);
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))

let newImage = UIGraphicsGetImageFromCurrentImageContext();

return newImage!

But all it does is stretching the image to fit 900x900 size, that's not what I want.

Any idea what can I do here?


Answer Source

You can crop from center of the image to 900 pixel if the image size is larger than 900.

Here is the code :

func centerCropImage(image1:UIImage) -> UIImage

    let modifiedSize:CGFloat = 900.0;
    // Center the crop area

    let clippedRect = CGRect(x: ((image.size.width - modifiedSize)/2), y: ((image.size.height - modifiedSize)/2), width: modifiedSize, height: modifiedSize);

    // Crop logic
    let imageRef:CGImage = image.cgImage!.cropping(to: clippedRect)!;

    //(image as! CGImage).cropping(to: clippedRect)!;
    let croppedImage = UIImage(cgImage: imageRef);

    return croppedImage;

Hope it helps

Happy coding ...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download