用一根手指iPhone,iPad旋转UIView

时间:2012-07-06 19:20:06

标签: cocoa rotation cgaffinetransform uipangesturerecognizer

我实现了一个UIPanGestureRecognizer,因为我希望用一根手指沿其轴旋转UIView。 uiview中的按钮开始UIView旋转的手势。问题是,如果按钮位于第一个象限,左上角,它只能正确旋转。任何其他象限,它不规则地旋转。有人能告诉我数学有什么问题。顺便说一句,ang使用superview的坐标计算角度,因为用户手指可能在旋转视图范围之外,但这可能没有必要。

谢谢

- (void)rotateItem:(UIPanGestureRecognizer *)recognizer
{
    NSLog(@"Rotate Item");

    float ang = atan2([recognizer locationInView:self.superview].y - self.center.y, [recognizer locationInView:self.superview].x - self.center.x);

    float angleDiff = deltaAngle - ang;
    self.transform = CGAffineTransformRotate(startTransform, -angleDiff);

    CGFloat radians = atan2f(self.transform.b, self.transform.a);
    NSLog(@"rad is %f", radians);
}

#pragma mark - Touch Methods

- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)recognizer
{

    if (recognizer == rotateGesture) {
        NSLog(@"rotate gesture started");

        deltaAngle = atan2([recognizer locationInView:self].y-self.center.y, [recognizer locationInView:self].x-self.center.x);

        startTransform = self.transform;
    }

    return YES;
}

1 个答案:

答案 0 :(得分:0)

我做了一些日志记录,似乎我的uiview中心在触摸拖动事件期间发生了变化。因此,我使用touches begin方法存储了uiview的中心并使用了它。

- (void)rotateItem:(UIPanGestureRecognizer *)recognizer
    {
        NSLog(@"Rotate Item");

        CGPoint superPoint = [self convertPoint:itemCenter toView:self.superview];

        float ang = atan2([recognizer locationInView:self.superview].y - superPoint.y, [recognizer locationInView:self.superview].x - superPoint.x);

        float angleDiff = deltaAngle - ang;
        self.transform = CGAffineTransformRotate(startTransform, -angleDiff);

    }

    #pragma mark - Touch Methods

    - (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)recognizer
    {

        if (recognizer == rotateGesture) {
            NSLog(@"rotate gesture started");

            deltaAngle = atan2([recognizer locationInView:self.superview].y-self.center.y, [recognizer locationInView:self.superview].x-self.center.x);

            startTransform = self.transform;
        }

        return YES;
    }