征服iOS常看

UIScrollView双击定点放大、双指缩放

2016-06-08  本文已影响2020人  jzhang

我这里是封装的一个单独的UIScrollView,用在制作相册的时候使用。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpViews];
    }
    return self;
}
- (void)setUpViews {
    self.delegate = self;//一定要遵守代理
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    //设置最大放大倍数
    self.minimumZoomScale = 1.0;
    self.maximumZoomScale = 2.0;
    //粘贴一张图片
    _imageView = [[UIImageView alloc] init];
    _imageView.frame = CGRectMake(0, 0, self.frame.size.width - 10*2, self.frame.size.height);
    _imageView.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    //添加双击事件
    UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTapGesture setNumberOfTapsRequired:2];
    [_imageView addGestureRecognizer:doubleTapGesture];
    _imageView.userInteractionEnabled = YES;
    [self addSubview:_imageView];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
    CGFloat zoomScale = self.zoomScale;
    zoomScale = (zoomScale == 1.0) ? 2.0 : 1.0;
    CGRect zoomRect = [self zoomRectForScale:zoomScale withCenter:[gesture locationInView:gesture.view]];
    [self zoomToRect:zoomRect animated:YES];
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height =self.frame.size.height / scale;
    zoomRect.size.width  =self.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  /2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height /2.0);
    return zoomRect;
}

这样就实现了这两个功能。写的时候遇到一个坑点,一开始我在放置ImageView的时候,设置frame是放在layoutSubviews方法里面,结果缩放有问题,估计是因为layoutSubviews被调用了多次的原因。

上一篇下一篇

猜你喜欢

热点阅读