在cocos2d里面处理的触摸事件都定义在CCLayer的CCStandardTouchDelegate跟CCTargetedTouchDelegate里面。其中对于CCTargetedTouchDelegate的解释是dispatcher会把一个NSSet的触摸事件都拆分好,用户只需要处理一个UITouch就可以了,说是可以更好的处理多点触摸。但是这次我用的是CCStandardTouchDelegate,跟CocoaTouch中处理触摸事件的delegate是一样的,定义如下:
1 | @protocol CCStandardTouchDelegate <NSObject> |
3 | - ( void )ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; |
4 | - ( void )ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; |
5 | - ( void )ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; |
6 | - ( void )ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; |
以下是几种常用的手势。
pinch zoom
用2根手指缩放图片,这个动作应该是非常常用的了。
- 首先要在touchBegan的时候,算出2指的初始距离。
01 | if ([touches count] == 2) { |
03 | NSArray *twoTouch = [touches allObjects]; |
04 | UITouch *tOne = [twoTouch objectAtIndex:0]; |
05 | UITouch *tTwo = [twoTouch objectAtIndex:1]; |
06 | CGPoint firstTouch = [tOne locationInView:[tOne view]]; |
07 | CGPoint secondTouch = [tTwo locationInView:[tTwo view]]; |
09 | initialDistance = sqrt ( pow (firstTouch.x - secondTouch.x, 2.0f) + pow (firstTouch.y - secondTouch.y, 2.0f)); |
- 然后在touchMoved算一下是该zoom in还是out。
01 | if ([touches count] == 2) { |
02 | NSArray *twoTouch = [touches allObjects]; |
04 | UITouch *tOne = [twoTouch objectAtIndex:0]; |
05 | UITouch *tTwo = [twoTouch objectAtIndex:1]; |
06 | CGPoint firstTouch = [tOne locationInView:[tOne view]]; |
07 | CGPoint secondTouch = [tTwo locationInView:[tTwo view]]; |
08 | CGFloat currentDistance = sqrt ( pow (firstTouch.x - secondTouch.x, 2.0f) + pow (firstTouch.y - secondTouch.y, 2.0f)); |
10 | if (initialDistance == 0) { |
11 | initialDistance = currentDistance; |
13 | } else if (currentDistance - initialDistance > 0) { |
15 | if (currentImage.scale < 1.0f) { |
16 | zoomFactor += zoomFactor *0.03f; |
17 | currentImage.scale = zoomFactor; |
20 | initialDistance = currentDistance; |
21 | } else if (currentDistance - initialDistance < 0) { |
23 | if (currentImage.scale > 0.45f) { |
24 | zoomFactor -= zoomFactor *0.03f; |
25 | currentImage.scale = zoomFactor; |
28 | if (currentImage.position.x > [currentImage boundingBox].size.width / 2 || |
29 | currentImage.position.x < 320 - [currentImage boundingBox].size.width / 2 || |
30 | currentImage.position.y > [currentImage boundingBox].size.height / 2 || |
31 | currentImage.position.y < 480 - [currentImage boundingBox].size.height / 2) { |
32 | currentImage.position = ccp(160,240); |
35 | initialDistance = currentDistance; |
上面在zoom out最后要判断一下缩小后的position是不是已经在显示框以外了,如果是的话要把它修正。