如何旋转手指后的UIButton或UIImage视图(触摸并按住)?

时间:2011-02-11 21:34:40

标签: iphone objective-c ipad

我需要一些帮助。如何旋转跟随手指的UIButton或UIImageView(触摸并按住,UILongPressGestureRecognizer)? Thx 4帮助

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

}

2 个答案:

答案 0 :(得分:0)

很高兴我记得三角法


-(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.

这几乎是你需要的所有代码。数学是正确的,但我不确定setTransform的东西。我在学校用浏览器写这个。你应该能够从这里弄明白。

祝你好运,

Aurum Aquila

答案 1 :(得分: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;
}