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