简体   繁体   中英

UIScrollView zoom is not working properly

Whenever I click on an image, I want the image to display as a larger image with the ability to zoom. So far when I click on the image, it displays as I want it to inside a scrollview. However, I have to get lucky to be able to zoom in properly. Most of the time when I attempt to zoom, the image just moves down and to the right and does not zoom at all. Here is my code:

-(void) pictureButtonAction 
{
    self.scrollImageView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.scrollImageView.contentSize = self.fullImageView.image.size;
    self.scrollImageView.delegate = self;
    self.scrollImageView.clipsToBounds = YES;
    self.scrollImageView.scrollEnabled = YES;
    [self.scrollImageView setMaximumZoomScale:4.0f];
    [self.scrollImageView setMinimumZoomScale:1.0f];
    [self.view addSubview:self.scrollImageView];
    [self.scrollImageView addSubview:fullImageView];
}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView 
{
    return self.fullImageView;
}

ImageViews frame got changed while zooming , so that it moves down. So, You have to centralize the image view each time you zoom .

your scrollviews contentsize should be greater than or equal to your image size , if your fullImageView.image.size is less than your scrollviews bounds ,then set your scrollviews contentSize atleast double the scrollviews bounds .

call the below function in scrollViewDidZoom delegate method

-(void) centerScrollViewContents
{
    CGSize boundsSize = self.scrollView.bounds.size;
    CGRect contentsFrame = self.imageView.frame;

    if (contentsFrame.size.width < boundsSize.width) {
        contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
    } else {
        contentsFrame.origin.x = 0.0f;
    }

    if (contentsFrame.size.height < boundsSize.height) {
        contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
    } else {
        contentsFrame.origin.y = 0.0f;
    }

    self.imageView.frame = contentsFrame;
}

Try this , hope it will help you ; happy coding ! :)

@Maria's answer works but when zooming you'll experience unwanted bounces, instead of using it under scrollViewDidZoom , use scrollViewDidEndZooming: delegate to prevent that..

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    [self centerScrollViewContents];
}

and with a little enhancement from her code:

[UIView animateWithDuration:0 animations:^{

    self.previewImageView.frame = contentsFrame;

}];

a bit late for an answer but i hope this will be useful to some..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM