这是封装的一个UITapGestureRecognizer,这里记录一下
主要思路
点击图片的时候,首先在window的keywindow上面再创建一个view,然后把图片等比例放大,放到上面,然后操作捏合,移动
UIWindow * window = [UIApplication sharedApplication].keyWindow;
backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, windowWidth, windowHeight)];
backView.backgroundColor = [UIColor blackColor];
backView.alpha = 0;
[window addSubview:backView];
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideBackView)];
[backView addGestureRecognizer:tap];
UIImageView * backImageView = (UIImageView *)self.view;
oldRect = backImageView.frame;
UIImageView * showImageView = [[UIImageView alloc]initWithFrame:[self.view convertRect:self.view.bounds toView:window]];
showImageView.image = backImageView.image;
showImageView.tag = 190231;
showImageView.userInteractionEnabled = YES;
[backView addSubview:showImageView];
//缩放手势
UIPinchGestureRecognizer * pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchAction:)];
[showImageView addGestureRecognizer:pinch];
//移动手势
UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
[showImageView addGestureRecognizer:pan];
//放大图片的主要代码
[UIView animateWithDuration:0.3 animations:^{
showImageView.frame = CGRectMake(0,(windowHeight - backImageView.image.size.height * windowWidth / backImageView.image.size.width) / 2, windowWidth, backImageView.image.size.height * windowWidth / backImageView.image.size.width);
backView.alpha = 1;
newRect = showImageView.frame;
}];
下面是手势完成的主要操作
缩放手势这里关键是找到放大的比例,首先要理清楚要放大的倍数是多少,如果直接使用sender.scale 这样就是在前一次放大的基础上,再次放大那么多倍,而我们实际要的效果是在前一次放大的基础上,再放大移动的数值,所以每次手指移动放大的倍数应该是上次的sender.scale值减去当前的sender.scale
UIImageView * showImageView = (UIImageView *)[backView viewWithTag:190231];
if (sender.state == UIGestureRecognizerStateBegan) {
pinchChangeValue = 1;
return;
}
CGFloat change = 1 - (pinchChangeValue - sender.scale);
showImageView.transform = CGAffineTransformScale(showImageView.transform, change, change);
//记录当前比例
pinchChangeValue = sender.scale;
移动手势
//这里和缩放差不多相同的原理
if (sender.state == UIGestureRecognizerStateBegan) {
panChangeValueOld = sender.view.center;
return;
}
if (sender.state == UIGestureRecognizerStateChanged) {
CGPoint translation = [sender translationInView:self.view];
float newY = panChangeValueOld.y + translation.y;
float newX = panChangeValueOld.x + translation.x;
sender.view.center = CGPointMake(newX, newY);
}
最后是点击收起图片:
这里要处理两次的隐藏,点击的时候判断图片是否被放大了,如果被缩放手势放大的话,先变为点击放大后的尺寸,再变为原先尺寸,如果没有被缩放手势放大,则直接变为原来尺寸
UIImageView * showImageView = (UIImageView *)[backView viewWithTag:190231];
if (showImageView.frame.size.width > newRect.size.width) {
[UIView animateWithDuration:0.3 animations:^{
showImageView.frame = newRect;
}];
}else{
[UIView animateWithDuration:0.3 animations:^{
showImageView.frame = oldRect;
backView.alpha = 0;
} completion:^(BOOL finished) {
[backView removeFromSuperview];
}];
}
本次练习的demo的地址:demo