Rotation gesture produces undesired rotation

前端 未结 2 1589
抹茶落季
抹茶落季 2021-01-22 07:15

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:



        
相关标签:
2条回答
  • 2021-01-22 07:50

    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.

    0 讨论(0)
  • 2021-01-22 08:00

    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
        }
    
    0 讨论(0)
提交回复
热议问题