I need to rotate an UIImageview on user\'s motion using just one finger motion. For that I use a rotation gesture and then override touchesMoved with this code:
The problem is that you are saying
rotateImageView.transform = CGAffineTransformMakeRotation(angle)
So whatever transform the image view has already (from the previous rotation) is thrown away and completely replaced by a new transform starting at angle
. That's the "jump" you are seeing.
What you want to do is apply a rotation transform to the existing transform of the image view. You can do that by calling CGAffineTransformRotate, instead of CGAffineTransformMakeRotation.
you may want to change self.superview to self.view (mine is subclass)
var xOffSet:CGVector = CGVectorMake(0, 0)
var yOffSet:CGVector = CGVectorMake(0, 0)
var origin:CGPoint = CGPointZero
var tempTransform=CGAffineTransform()
var startingAngle:CGFloat?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
origin = (touches.first?.locationInView(self.superview))!
xOffSet = CGVector(dx:(origin.x)-self.center.x, dy:(origin.y) - self.center.y)
startingAngle = atan2(xOffSet.dy,xOffSet.dx)
//save the current transform
tempTransform = self.transform
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touchPoint = touches.first?.locationInView(self.superview)
yOffSet = CGVector(dx:touchPoint!.x - self.center.x, dy:touchPoint!.y - self.center.y)
let angle = atan2(yOffSet.dy,yOffSet.dx)
let deltaAngle = angle - startingAngle!
self.transform = CGAffineTransformRotate(tempTransform, deltaAngle)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
startingAngle = nil
}
//reset in case drag is cancelled
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
self.transform = tempTransform
startingAngle = nil
}