使用 UIScrollView 进行放大和缩小视图

Posted

技术标签:

【中文标题】使用 UIScrollView 进行放大和缩小视图【英文标题】:Making zoom-in & out view with UIScrollView 【发布时间】:2014-03-24 02:58:08 【问题描述】:

我正在尝试使用 UIScrollView 制作一些放大和缩小视图。 这就像第一次点击使视图放大 3 倍,再点击一次使其再次放大 3 倍,然后再点击将其缩小回原始大小。 但是我的代码不能正常工作。 这有什么问题? 谢谢,

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
@property (strong, nonatomic) IBOutlet UIImageView *myImageView;


@end

@implementation ViewController

- (void)viewDidLoad

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.myScrollView.delegate = self;

    self.myScrollView.minimumZoomScale = 1;
    self.myScrollView.maximumZoomScale = 8;

    self.myScrollView.scrollEnabled = YES;
    self.myScrollView.showsHorizontalScrollIndicator = YES;
    self.myScrollView.showsHorizontalScrollIndicator = YES;



    UITapGestureRecognizer  *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];

    doubleTapGesture.numberOfTapsRequired = 2;
    self.myImageView.userInteractionEnabled = YES;
    [self.myImageView addGestureRecognizer:doubleTapGesture];







- (void)didReceiveMemoryWarning

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.




- (void)doubleTap:(UITapGestureRecognizer *)gesture


    if (self.myScrollView.zoomScale < self.myScrollView.maximumZoomScale)

        float newScale = self.myScrollView.zoomScale * 3;
        CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gesture locationInView:gesture.view]];

        [self.myScrollView zoomToRect:zoomRect animated:YES];

    else

        [self.myScrollView setZoomScale:1.0 animated:YES];
    



- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center

    CGRect zoomRect;
    zoomRect.size.height = [self.myScrollView frame].size.height * scale;
    zoomRect.size.width =  [self.myScrollView frame].size.width  * scale;

    zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.width / 2.0);

    return zoomRect;








#pragma mark - delegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView

    return self.myImageView;




@end

【问题讨论】:

【参考方案1】:
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center

    CGRect zoomRect;
    zoomRect.size.height = [self.myScrollView frame].size.height / scale;
    zoomRect.size.width =  [self.myScrollView frame].size.width  / scale;

    zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.width / 2.0);

    return zoomRect;



【讨论】:

以上是关于使用 UIScrollView 进行放大和缩小视图的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 UIScrollView 捕捉缩放?

放大时只允许 UIScrollView 缩放弹跳,不能缩小

UIScrollView 放大固定点,并禁用捏合/拉出

UIScrollView 和 zoomScale

在 UIScrollView 上放大时 UIButton 边框消失

当用户放大 UIScrollView 时如何隐藏某些内容,然后在缩小时显示它?