我将ImageView放入ViewController中,并且想用Pinch Gesture放大或缩小。另外,我想在用户双击图像时获得初始视图。我按照本教程Make Gallery
如果我仅使用捏合手势就能正常工作,则可以放大直到达到最大缩放,然后缩小直到达到最小缩放。右图为下图。
虽然,如果我双击ImageView,ImageView会获得其初始格式(图片1),但无法识别最小缩放的效果;如果我继续用捏手势进行缩小,则ImageView会继续缩小,并且我会得到此结果(图片2):
这些是我处理事件的方法:
@interface ImageGalleryViewController (){
NSString *productName;
CGFloat previousScale;
CGFloat previousRotation;
CGFloat beginX;
CGFloat beginY;
CGFloat scale;
//CGFloat __previousScale;
}
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
scale=1.0;
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scaleImage:)];
[self.view addGestureRecognizer:pinchGesture];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resetImage:)];
tapGesture.numberOfTapsRequired=2;
[self.view addGestureRecognizer:tapGesture];
}
- (void)resetImage:(UITapGestureRecognizer *)recognizer{
[UIView animateWithDuration:0.3 animations:^() {
self.view.transform = CGAffineTransformIdentity;
}];
self.bigImage.transform = CGAffineTransformIdentity;
[self.bigImage setCenter: CGPointMake(self.view.frame.size.width/2,self.view.frame.size.height/2+32)];
[UIView commitAnimations];
}
- (void)scaleImage:(UIPinchGestureRecognizer *)recognizer{
NSLog(@"Scale: %f", [recognizer scale]);
if ([recognizer state] == UIGestureRecognizerStateBegan) {
previousScale = scale;
}
CGFloat currentScale = MAX(MIN([recognizer scale] * scale, 10), 1);
CGFloat scaleStep = currentScale / previousScale;
[self.view setTransform: CGAffineTransformScale(self.view.transform, scaleStep, scaleStep)];
previousScale = currentScale;
if ([recognizer state] == UIGestureRecognizerStateEnded ||
[recognizer state] == UIGestureRecognizerStateCancelled ||
[recognizer state] == UIGestureRecognizerStateFailed) {
// Gesture can fail (or cancelled?) when the notification and the object is dragged simultaneously
scale = currentScale;
NSLog(@"Final scale: %f", scale);
}
}
那么,如果实现了初始右视图(第一张图像),如何停止缩小?
最佳答案
我不得不将变量重置为1.0到resetImage方法中。所以现在它可以正常工作了。