Force clockwise/anticlockwise rotation for a CABasicAnimation of a UIImageView

前端 未结 4 1164
清酒与你
清酒与你 2021-02-15 12:46

I\'m animating a pendulum which swings from 0 degrees to max 200 degrees and then back again. The problem is that if the pendulum goes over 180 degrees, it returns to 0 by the s

相关标签:
4条回答
  • 2021-02-15 13:13

    Try setting something like

    rotationAnimation.valueFunction = [CAValueFunction functionWithName:kCAValueFunctionRotateZ];
    

    Using value transform functions, animations can effect the transform property of a layer using arbitrary transforms of each component (no normalization to 360°) and concatenate in the normally when multiple animations are applied at once.

    You use a value transform function that rotates from 0° to 180° around the z-axis by creating a CAValueTransform function specifying the kCAValueFunctionRotateZ and then creating an animation with a fromValue of 0, a toValue of M_PI, and set the animation’s valueTransform property to the value transform instance.

    0 讨论(0)
  • 2021-02-15 13:30

    I think you have to use this code:

    [rotationAnimation.byValue = [NSNumber numberWithFloat:degreesToRadians(kMax/2))];
    [rotationAnimation.toValue = [NSNumber numberWithFloat:degreesToRadians(kMin)];
    
    0 讨论(0)
  • 2021-02-15 13:34

    I'm not sure exactly what the issue is, but if you use the animation's auto reverse feature, you can probably simplify this and cause it to rotate (swing) back and forth. This works for me:

    CABasicAnimation* rotationAnimation = 
              [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    [rotationAnimation setToValue:[NSNumber numberWithFloat:DegreesToRadians(200.0)]];
    [rotationAnimation setDuration:1.0];
    [rotationAnimation setRepeatCount:HUGE_VALF]; // Repeat forever
    [rotationAnimation setAutoreverses:YES]; // Return to starting point
    
    [[pendulum layer] addAnimation:rotationAnimation forKey:nil];
    
    0 讨论(0)
  • 2021-02-15 13:36

    To get it to go anticlockwise, just set x to a negative value (add - in front) where you want

    rotationAnimation.toValue = [NSNumber numberWithFloat:degreesToRadians(x)];
    
    0 讨论(0)
提交回复
热议问题