2011-02-11 89 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