geminiCoder
geminiCoder

Reputation: 2906

CALayer transforming

I need to rotate a square when the user does a UIRotationGesture.

I have the gesture all set up. The problem is every time the user moves their fingers the square returns to the starting position and then animates to the new position. Rather than move from the previous position to the new position.

i.e if the rotation of the square is 90 degrees and the user continues to rotate to 100. the square will go back to 0 degrees and animate to 100.

Essentially I want the square to mirror the user when they perform a rotate gesture.

- (void)respondToGesture:(UIRotationGestureRecognizer *)rec{

NSLog(@"Rotation: %f", rec.rotation);

[self rotateWithRadian:rec.rotation];

if (rec.state == UIGestureRecognizerStateEnded) {
    NSLog(@"gesture ended");
}

}



- (void)rotateWithRadian:(float)radian{

CABasicAnimation *spin = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];

spin.removedOnCompletion = NO;

spin.fillMode = kCAFillModeForwards;

[spin setByValue:[NSNumber numberWithFloat:radian]];

[spin setDuration:1.0];

[squarelayer addAnimation:spin forKey:@"spinAnimation"];

Upvotes: 0

Views: 2614

Answers (2)

mohsenr
mohsenr

Reputation: 7255

Is there a reason you're not directly setting the layer's transform instead of using an animation?

This should do what you want:

- (void)respondToGesture:(UIRotationGestureRecognizer *)rec {
    if (rec.state == UIGestureRecognizerStateChanged) {
        CGAffineTransform currentTransform = squareLayer.affineTransform;
        squareLayer.affineTransform = CGAffineTransformRotate(currentTransform, gesture.rotation);
        gesture.rotation = 0;
    }
}

You also need to adjust squareLayer.anchorPoint if you want the rotation to happen around the centre of the user's rotation instead of the centre of the layer.

Upvotes: 2

Vignesh
Vignesh

Reputation: 10251

There is a open source ( https://github.com/kirbyt/KTOneFingerRotationGestureRecognizer )for single finger rotation. You can check it out, will be much better. Even if you want only normal rotation gesture, you can look into the code for better rotation code. It uses center as origin.

Upvotes: 1

Related Questions