Objective-c – UIImageView pinch zooming in UIScrollView

iphoneobjective cuiimageviewuiscrollviewzooming

I am comfortable with pinch zooming functionality using UIScrollView. But the problem is the aspect fit of image in scrollview.

Currently, I am having this, below image:

enter image description here

But I want image to be fit in screen like below image:

enter image description here

And same behavior for landscape. How can I achieve this?

Below is the code:

- (void)viewDidLoad
{
    UIImage *image = [UIImage imageWithData:appDelegate.selectedOriginalImage];
    imgView.image = image;
    CGSize imageSize = image.size;
    CGRect rect = CGRectMake(0, 0, imageSize.width, imageSize.height);
    imgView.frame = rect;
    scrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height);
    scrollView.maximumZoomScale = 4.0;
    scrollView.minimumZoomScale = 1.0;
    scrollView.delegate = self;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    UIImage *image = [UIImage imageWithData:appDelegate.selectedOriginalImage];
    CGSize imageSize = image.size;
    CGRect rect = CGRectMake(0, 0, imageSize.width, imageSize.height);
    imgView.frame = rect;

    [scrollView setContentOffset:CGPointMake(0, 0)]; 

    return YES;
}

Best Answer

You are setting the UIImageView to the original size of the image instead of the size of the UIScrollView that contains it.

- (void)viewDidLoad
{
    UIImage *image = [UIImage imageWithData:appDelegate.selectedOriginalImage];
    imgView.image = image;

    imgView.frame = scrollView.bounds;
    [imgView setContentMode:UIViewContentModeScaleAspectFit];
    scrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height);
    scrollView.maximumZoomScale = 4.0;
    scrollView.minimumZoomScale = 1.0;
    scrollView.delegate = self;
}

remember to return the imgView on the viewToZoom delegate method

Related Topic