Spin UIImageView continuously

2020-05-19 02:34发布

问题:

I am having a problem while trying to rotate UIImageview continuously with a ball's image inside. I would like this ball to spin continuously on its center axis. I have tried using CGAffineTransform but it didn't work.

Please help!

回答1:

It should work if you use transforms as:

itemToRotate.transform = CGAffineTransformRotate(itemToRotate.transform, currentAngle);

I've uploaded some sample code of a working solution. Add your logic to rotate it automatically...



回答2:

This may be an old Q but it's near the top of search results for the topic. Here's a more cut and dry solution: (make sure to import QuartzCore/QuartzCore.h)

CABasicAnimation *rotation;
rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotation.fromValue = [NSNumber numberWithFloat:0];
rotation.toValue = [NSNumber numberWithFloat:(2*M_PI)];
rotation.duration = 1.1; // Speed
rotation.repeatCount = HUGE_VALF; // Repeat forever. Can be a finite number.
[yourView.layer addAnimation:rotation forKey:@"Spin"];

Then, to stop remove/reset the animation: (see comments for how to stop-in-place)

[yourView.layer removeAnimationForKey:@"Spin"];

In swift:

let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.fromValue = 0
rotation.toValue = 2 * M_PI
rotation.duration = 1.1
rotation.repeatCount = Float.infinity
view.layer.addAnimation(rotation, forKey: "Spin")