如何使用UIPanGestureRecognizer旋转图像

时间:2015-08-24 06:18:39

标签: ios objective-c xcode

嗯,这似乎很容易,但我已经花了好几个小时试图做到这一点。 我正在尝试开发一个圆形控件,带有图像并旋转控件,就像大音响设备的音量控制一样。然后,为了旋转图像,我使用了UIPanGestureRecognizerATAN2

使用图像的中心,如0,0坐标,以及图像的原点和大小来测量我的动作区域。从图像中心(我的0,0)计算出与X和Y的角度。如果Touch超出了图像的边界,则什么都不做,但如果在图像内部,我想要旋转它,但是,仍然没有工作。 编辑:我不想在这个程序中使用两个手指,我只需要用一根手指。

UIRotateGestureRecognizer使用两个,可以采用这种方式。

这是我的代码:

@property (strong, nonatomic) IBOutlet UIImageView *myMainIndicatorRoulett;

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanWithGestureRecognizer:)];
        [self.myTestView addGestureRecognizer:panGestureRecognizer];

        _myMainIndicatorRoulett.image = [TheColoristImages imageOfColorIndicatorWithIndicatorAngle:(CGFloat)90.0];

    }



-(void)handlePanWithGestureRecognizer:(UIPanGestureRecognizer *)panGestureRecognizer
    {
        double a1;
        double a2;

        a1 = [panGestureRecognizer locationInView:self.view].x;
        a2 = [panGestureRecognizer locationInView:self.view].y;

        double b1;
        double b2;

        b1 = _myMainIndicatorRoulett.frame.origin.x;
        b2 = _myMainIndicatorRoulett.frame.origin.y;

        double c1;
        double c2;

        c1 = b1 + _myMainIndicatorRoulett.frame.size.width;
        c2 = b2 + _myMainIndicatorRoulett.frame.size.height;

        if ((a1 > b1) && (a1 < c1) && (a2 > b2) && (a2 < c2))
        {
            double Cx;
            double Cy;
            Cx = _myMainIndicatorRoulett.center.x;
            Cy = _myMainIndicatorRoulett.center.y;

            double Tx;
            double Ty;
            Tx = [panGestureRecognizer locationInView:self.view].x - Cx;
            Ty = [panGestureRecognizer locationInView:self.view].y - Cy;
            double myAngle = atan2(Ty, Tx);

            _myMainIndicatorRoulett.transform = CGAffineTransformRotate(_myMainIndicatorRoulett.transform, myAngle * 3.14 / 180);
        }
    }

2 个答案:

答案 0 :(得分:2)

你的问题在最后一行:

_myMainIndicatorRoulett.transform = CGAffineTransformRotate(_myMainIndicatorRoulett.transform, myAngle * 3.14 / 180);

当你使用CGAffineTransformRotate(s,a)时,它会添加该角度,不会设置它。这就是为什么它会发疯的原因。每当你调用该函数时,它都会添加&#34; myAngle&#34;旋转度,使它看起来像旋转。你想设置角度。

你想用这个:

_myMainIndicatorRoulett.transform = CGAffineTransformMakeRotation(myAngle);

答案 1 :(得分:0)

UIView上的一个手指旋转:https://github.com/kirbyt/KTOneFingerRotationGestureRecognizer 检查这个repo,它是一个自定义的gestureRecognizer,可以为你处理单指旋转。