UIImage resize aspect fill and crop UIImage resize aspect fill and crop objective-c objective-c

UIImage resize aspect fill and crop


Try this:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{    imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];    double width = imagenUsr.size.width;    double height = imagenUsr.size.height;    double screenWidth = self.view.frame.size.width;    double apect = width/height;    double nHeight = screenWidth/ apect;    self.imgView.frame = CGRectMake(0, 0, screenWidth, nHeight);    self.imgView.center = self.view.center;    self.imgView.image = imagenUsr;}

This will help you keeping the aspect ratio as before.

Another way would be:

self.imgView.contentMode = UIViewContentModeScaleAspectFit;self.imgView.image = imagenUsr;

Hope this helps.. :)


Swift 3.0 / 4.0

AspectFill image cropping/Resizing... according to UIImageview Frame Size.

    func ResizeImage(with image: UIImage?, scaledToFill size: CGSize) -> UIImage? {    let scale: CGFloat = max(size.width / (image?.size.width ?? 0.0), size.height / (image?.size.height ?? 0.0))    let width: CGFloat = (image?.size.width ?? 0.0) * scale    let height: CGFloat = (image?.size.height ?? 0.0) * scale    let imageRect = CGRect(x: (size.width - width) / 2.0, y: (size.height - height) / 2.0, width: width, height: height)    UIGraphicsBeginImageContextWithOptions(size, false, 0)    image?.draw(in: imageRect)    let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()    UIGraphicsEndImageContext()    return newImage}


EDIT: Not sure if I missed this or it was edited, but I didn't see that you wanted to crop it as well. Rashad's solution should work for you.

Have you tried creating an image view with the image and adding it to the view?

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {    imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];    imageView.image = imagenUsr;    imageView.contentMode = UIViewContentModeScaleAspectFit;    [self.view addSubview:imageView];}