2011-02-11 40 views
0

我需要一些幫助。如何旋轉跟隨手指的UIButton或UIImageView(觸摸並按住UILongPressGestureRecognizer)? Thx 4幫助如何旋轉跟隨手指的UIButton或UIImage視圖(觸摸並按住)?

UPD:不明白我在做什麼錯了?

- (void)viewDidLoad { 

UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]; 
[self.view addGestureRecognizer:tapgr]; 
[tapgr release];  
[super viewDidLoad]; 

}

-(void)tap:(UITapGestureRecognizer *)gesture { 

CGPoint touch = [gesture locationInView:self.view]; 
CGPoint center = myImage.center; 
float dx,dy,wtf; 
dx = touch.x-center.x; 
dy = touch.y-center.y; 
wtf = atan2f(dy, dx); 

[self rotateImage:self.myImage withAngle:wtf]; 

}

- (void)rotateImage:(UIImageView *)image withAngle:(float)newAngle 

{ image.transform = CGAffineTransformMakeRotation(newAngle);

}

回答

0
- (void) LongPress:(UILongPressGestureRecognizer *)gesture { 

    CGPoint p = [gesture locationInView:self.view]; 

    CGPoint zero; 
    zero.x = self.view.bounds.size.width/2.0; 
    zero.y = self.view.bounds.size.height/2.0; 

    CGPoint newPoint; 

    newPoint.x = p.x - zero.x; 
    newPoint.y = zero.y - p.y; 

    angle = atan2(newPoint.x, newPoint.y); 



    UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionAllowUserInteraction; 

    [UIView animateWithDuration:0.2 delay:0.0 options:options 
        animations:^{myButton.transform = CGAffineTransformRotate(CGAffineTransformIdentity, angle);} 
        completion:^(BOOL finished) { 
         [UIView animateWithDuration:1.0 delay:0.5 options:options animations:^{ 
          myButton.transform = CGAffineTransformRotate(CGAffineTransformIdentity, [self detectQuarter:angle]); 
         } completion:nil]; 
        }]; 
} 

#define M_PI_3_4 3*M_PI_4 

-(CGFloat)detectQuarter:(CGFloat)anAngle { 
    if ((anAngle >= -M_PI_4)&&(anAngle <= M_PI_4)) return 0; 
    if ((anAngle > M_PI_4) && (anAngle <= 3*M_PI_4)) return M_PI_2; 
    if ((anAngle >= -M_PI_3_4) && (anAngle < -M_PI_4)) return -M_PI_2; 
    else return M_PI; 
} 
0

很高興我記得triginometry


-(void)degreesToRotateObjectWithPosition:(CGPoint)objPos andTouchPoint:(CGPoint)touchPoint{ 

    float dX = touchPoint.x-objPos.x;  // distance along X 
    float dY = touchPoint.y-objPos.y;  // distance along Y 
    float radians = atan2(dY, dX);   // tan = opp/adj 

    //Now we have to convert radians to degrees: 
    float degrees = radians*M_PI/360; 

    return degrees; 
} 

一旦你有你的好方法,只是這樣做的觸摸事件的方法。 (我忘了叫什麼了...)

CGAffineTransform current = view.transform; 

[view setTransform:CGAffineTransformRotate(current,
[self degreesTorotateObjectWithPosition:view.frame.origin
andTouchPoint:[touch locationInView:parentView]] //Note: parentView = The view that your object to rotate is sitting in.

這是幾乎所有你會need.The數學是正確的代碼,但我不知道的東西的setTransform。我在學校用瀏覽器寫這篇文章。你應該能夠從這裏弄清楚。

祝你好運,

奧羅拉奎拉

+0

THX是什麼聯繫嗎? – 2011-02-12 00:07:42