开发者

Smooth rotation of UIView with touch

开发者 https://www.devze.com 2023-02-17 11:58 出处:网络
I\'m wondering how to smooth a UITouch in my code. I am able to detect the UItouch on my UIView, but when I try to rotate the view using CGAffineTransform, it does not rotate smoothly. I have to press

I'm wondering how to smooth a UITouch in my code. I am able to detect the UItouch on my UIView, but when I try to rotate the view using CGAffineTransform, it does not rotate smoothly. I have to press or long finger touch on iPhone for this kind of rotation. How can I perform smooth rotations, like Roambi V开发者_开发知识库isualizer app. Thanks for your help.


transform is an animatable property of UIView, so you can use Core Animation to make the rotation smooth:

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


Hi all I found following solution to my question and its works for me in touchesMoved.....

Here is the code....

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


This may or may not be long dead, but there are a few small issues with cam's answer.

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

needs to be

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

If you are looking to do this in swift, I used Cam's answer to figure out the following:

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消