2010-05-18 45 views
0

我正在開發模塊,其中我從照片庫中選取圖像並放入精靈。我想爲精靈圖像實現放大/縮小效果,就像相機圖像放大/縮小效果一樣。有人可以請指導我如何實施它?如何在cocos2d精靈圖片上實現放大/縮小效果?

我在某處看到的是,我必須在ccTouchBegan中檢測到兩個觸摸事件,然後根據兩根手指觸摸事件值的距離將精靈的縮放大小調整爲向上或向下。

可能有人請告訴我:

  • 如何檢測兩個手指在觸摸ccTouchBegan值?
  • 如何允許用戶觸摸和放大/縮小精靈圖像?請給我樣品。我嘗試了一些this URL的東西,但不適合我的要求。

謝謝。

+0

任何幫助添加這個好嗎?用適當的代碼我還沒有成功呢? – Getsy 2010-05-21 08:20:01

回答

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)第一步,你需要創建兩個變量。

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; 
     } 
    } 
}