我这里是封装的一个单独的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
被调用了多次的原因。