通过触摸平滑旋转UIView

时间:2011-03-18 12:54:50

标签: iphone objective-c iphone-sdk-3.0 uitouch cgaffinetransform

我想知道如何在代码中平滑UITouch。我能够检测到UItouch上的UIView,但是当我尝试使用CGAffineTransform旋转视图时,它无法顺利旋转。我必须按下或长按iPhone才能进行这种旋转。 如何进行平滑旋转,如Roambi Visualizer应用程序。 谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

transform是UIView的可动画属性,因此您可以使用Core Animation来使旋转平滑:

CGAffineTransform newTransform = //...construct your desired transform here...
[UIView animateWithDuration:0.2
                 animations:^{view.transform = newTransform;}];

答案 1 :(得分:1)

大家好我发现我的问题解决了以下问题,并且我在touchesMoved .....中找到了它。

这是代码......

UITouch *touch = [touches anyObject];
CGPoint currentLocation = [touch locationInView:self.superview];
CGPoint pastLocation = [touch previousLocationInView:self.superview];
currentLocation.x = currentLocation.x - self.center.x;
currentLocation.y = self.center.y - currentLocation.y;
pastLocation.x = pastLocation.x - self.center.x;
pastLocation.y = self.center.y - currentLocation.y;
CGFloat angle = atan2(pastLocation.y, pastLocation.x) - atan2(currentLocation.y, currentLocation.x); 
CGAffineTransform transform = CGAffineTransformMakeRotation(angle);

// Apply the affine transform

[[self.superview viewWithTag:ROTATE_VIEW_TAG] setTransform:transform] ;

答案 2 :(得分:1)

这可能会或可能不会很久,但是cam的答案有一些小问题。

 pastLocation.y = self.center.y - currentLocation.y;

需要

 pastLocation.y = self.center.y - pastLocation.y;

如果您想在swift中执行此操作,我使用Cam的答案来弄清楚以下内容:

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch: UITouch = touches.first as! UITouch

    var currentTouch = touch.locationInView(self.view)
    var previousTouch = touch.previousLocationInView(self.view)

    currentTouch.x = currentTouch.x - self.view.center.x
    currentTouch.y = self.view.center.y - currentTouch.y

    previousTouch.x = previousTouch.x - self.view.center.x
    previousTouch.y = self.view.center.y - previousTouch.y

    var angle = atan2(previousTouch.y, previousTouch.x) - atan2(currentTouch.y, currentTouch.x)

    UIView.animateWithDuration(0.1, animations: { () -> Void in
        bigCircleView?.transform = CGAffineTransformRotate(bigCircleView!.transform, angle)
    })

}