iOS UIScrollView雙擊定點放大、雙指縮放

我這里是封裝的一個單獨的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被調用了多次的原因。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容