UIScrollView缩放无法正常工作

时间:2014-12-10 06:34:48

标签: ios objective-c uiscrollview uiimageview

每当我点击图像时,我希望图像显示为具有缩放功能的较大图像。到目前为止,当我点击图像时,它会在滚动视图中显示为我想要的内容。但是,我必须幸运能够正确放大。大多数情况下,当我尝试缩放时,图像只是向下和向右移动,并且根本不会缩放。这是我的代码:

-(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;
}

2 个答案:

答案 0 :(得分:1)

ImageViews框架在变焦时发生了变化,因此向下移动。因此,每次缩放时都必须集中图像视图。

如果您的fullImageView.image.size小于您的滚动视图边界,则您的滚动视图内容大小应大于或等于您的图像大小,然后将您的滚动视图contentSize设置为滚动视图边界的两倍。

在scrollViewDidZoom委托方法

中调用以下函数
-(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;
}

试试这个,希望它会对你有所帮助;快乐的编码! :)

答案 1 :(得分:0)

@ Maria的答案有效,但在缩放时,您会遇到不必要的跳出,而不是在scrollViewDidZoom下使用它,请使用scrollViewDidEndZooming:委托以防止这种情况发生..

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

并从她的代码中略微增强:

[UIView animateWithDuration:0 animations:^{

    self.previewImageView.frame = contentsFrame;

}];

答案有点迟,但我希望这对某些人有用..

相关问题