捏合操作,实现图片(视图)的缩放效果,方法先判断是几点触控,当是一点触控时,不做出任何反应,多指暂时没管(因为没真机测试,只能苦逼的使用Xcode自带的支持两指的模拟器)
重写init初始化方法
- (instancetype)initWithFrame:(CGRect)frame{
// iOS 支持多点触摸,但是只能单点触摸
self = [super initWithFrame:frame];
if (self){
self.multipleTouchEnabled = YES;
}
return self;
}
实现缩放方法 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
if (1 == touches.count){
return;
}else{
// 1. 取出所有手指对象所在的集合
NSArray * allTouch = [touches allObjects];
// 2.获取两个手指对象
UITouch * touch1 = [allTouch firstObject];
UITouch * touch2 = [allTouch lastObject];
// 3.获取当前的手指位置
CGPoint currentFirstPoint = [touch1 locationInView:self];
CGPoint currentSecondPoint = [touch2 locationInView:self];
NSLog(@"currentFirstPoint:%f",currentFirstPoint.x);
NSLog(@"currentSecondPoint:%f",currentSecondPoint.x);
// 4.获取两个手指当前的距离
CGFloat currentDistance = [self distanFromPoint:currentFirstPoint toPoint:currentSecondPoint];
NSLog(@"currentDistance:%f",currentDistance);
// 5.获取之前两个手指的位置
CGPoint previousFirstPoint = [touch1 previousLocationInView:self];
CGPoint previousSecondPoint = [touch2 previousLocationInView:self];
// 6.获取之前两个手指之间的距离
CGFloat previousDistance = [self distanFromPoint:previousFirstPoint toPoint:previousSecondPoint];
NSLog(@"previousDistance:%f",previousDistance);
// 7.获取缩放前后的比例
CGFloat rate = currentDistance / previousDistance;
NSLog(@"rate:%f",rate);
// 8.缩放视图,如果视图的大小变化中心点不变,修改bounds就可以实现
self.bounds = CGRectMake(0, 0, self.frame.size.width * rate,self.frame.size.height * rate);
}
}
// 计算两点之间的位置的方法
- (CGFloat)distanFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint{
CGFloat dx = fromPoint.x - toPoint.x;
CGFloat dy = fromPoint.y - toPoint.y;
return sqrt(dx*dx + dy*dy);
}