How to Rotate an Uiimageview Using Touchesmoved

How can I rotate an UIImageView by 20 degrees?

A transformation matrix is not incredibly difficult. It's quite simple, if you use the supplied functions:

imgView.transform = CGAffineTransformMakeRotation(.34906585);

(.34906585 is 20 degrees in radians)


Swift 5:

imgView.transform = CGAffineTransform(rotationAngle: .34906585)

Rotate the image corresponding to the touch drag in iPhone

If you're targeting iOS 3.2 or greater, you can use UIRotationGestureRecognizer. The code would look something like this:

In your setup method (viewDidLoad or init, etc,):

UIRotationGestureRecognizer *rotationGesture = 
[[UIRotationGestureRecognizer alloc] initWithTarget:self
action:@selector(handleRotate:)];
rotationGesture.delegate = self;
[myImageView addGestureRecognizer:rotationGesture];
[rotationGesture release];

The event handler:

- (void)handleRotate:(UIRotationGestureRecognizer *)recognizer {
if(recognizer.state == UIGestureRecognizerStateBegan ||
recognizer.state == UIGestureRecognizerStateChanged)
{
recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform,
recognizer.rotation);
[recognizer setRotation:0];
}
}

I have some more examples of gesture recognizers (including the one above) on github.

Rotation gesture produces undesired rotation

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
}


Related Topics



Leave a reply



Submit