我正在开发模块where-in我从照片库中选择图像并放入精灵。我想为精灵图像实现放大/缩小效果,就像相机相册图像放大/缩小效果一样。有人可以指导我如何实施它?
我看到某处是,我必须在ccTouchBegan
中检测到两个触摸事件,然后根据两个手指触摸事件值的距离将精灵的比例大小调整为向上或向下。
有人可以告诉我:
ccTouchBegan
?谢谢。
答案 0 :(得分:1)
使用手势识别器进行缩放会更简单:
// on initializing your scene:
UIPinchGestureRecognizer* PinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget: self action: @selector (zoom:)];
[[[Director sharedDirector] openGLView] addGestureRecognizer: PinchGesture];
...
/// zoom callback:
-(void) zoom: (UIPinchGestureRecognizer*) gestureRecognizer
{
if (([gestureRecognizer state] == UIGestureRecognizerStateBegan) || ([gestureRecognizer state] == UIGestureRecognizerStateChanged))
yourSprite.scale = [gestureRecognizer scale];
}
答案 1 :(得分:1)
1)第一步,您需要创建两个变量。
BOOL canPinch;
float oldScale;
2)使用brigadir的:)回答并在init方法中添加
UIPinchGestureRecognizer* pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action: @selector (zoom:)];
[[[CCDirector sharedDirector] openGLView] addGestureRecognizer:pinchGesture];
3)
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray* allTouches = [[event allTouches] allObjects];
UITouch* touch = [touches anyObject];
CGPoint location = [self convertTouchToNodeSpace:touch];;
CGRect particularSpriteRect = CGRectMake(spriteToZoom.position.x-[spriteToZoom boundingBox].size.width/2, spriteToZoom.position.y-[spriteToZoom boundingBox].size.height/2, [spriteToZoom boundingBox].size.width, [spriteToZoom boundingBox].size.height);
if(CGRectContainsPoint(particularSpriteRect, location))
{
if ([allTouches count] == 2)
{
canPinch = YES;
return;
}
else if ([allTouches count] == 1)
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];
CGPoint translation = ccpSub(touchLocation, oldTouchLocation);
[self panForTranslation:translation];
}
}
canPinch = NO;
}
- (void)panForTranslation:(CGPoint)translation
{
CGPoint newPos = ccpAdd(spriteToZoom.position, translation);
spriteToZoom.position = newPos;
}
- (void)zoom: (UIPinchGestureRecognizer*) gestureRecognizer
{
if (canPinch)
{
if (([gestureRecognizer state] == UIGestureRecognizerStateBegan) || ([gestureRecognizer state] == UIGestureRecognizerStateChanged))
{
spriteToZoom.scale = oldScale + [gestureRecognizer scale]-(oldScale != 0 ? 1 : 0);
}
if ([gestureRecognizer state] == UIGestureRecognizerStateEnded)
{
oldScale = spriteToZoom.scale;
}
}
}