Ich versuche, UIImageView
um 360 Grad zu drehen, und habe mir online mehrere Tutorials angesehen. Ich könnte keine davon zum Laufen bringen, ohne dass die UIView
entweder anhält oder zu einer neuen Position springt.
Das Letzte, was ich versucht habe, ist:
[UIView animateWithDuration:1.0
delay:0.0
options:0
animations:^{
imageToMove.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
Aber wenn ich 2 * pi benutze, bewegt es sich überhaupt nicht (da es die gleiche Position ist). Wenn ich versuche, nur pi (180 Grad) zu machen, funktioniert es, aber wenn ich die Methode erneut aufrufe, dreht sie sich rückwärts.
EDIT :
[UIView animateWithDuration:1.0
delay:0.0
options:0
animations:^{
[UIView setAnimationRepeatCount:HUGE_VALF];
[UIView setAnimationBeginsFromCurrentState:YES];
imageToMove.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
funktioniert auch nicht. Es geht auf 180
Grad, hält für einen Sekundenbruchteil inne und wird dann auf 0
Grad zurückgesetzt, bevor es erneut gestartet wird.
Es wurde eine Methode gefunden (ich habe sie ein wenig modifiziert), die für mich perfekt funktioniert: iphone UIImageView rotation
#import <QuartzCore/QuartzCore.h>
- (void) runSpinAnimationOnView:(UIView*)view duration:(CGFloat)duration rotations:(CGFloat)rotations repeat:(float)repeat {
CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * rotations * duration ];
rotationAnimation.duration = duration;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = repeat ? HUGE_VALF : 0;
[view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
Ein großes Lob an Richard J. Ross III für die Idee, aber ich fand, dass sein Code nicht ganz das war, was ich brauchte. Die Standardeinstellung für options
ist, glaube ich, UIViewAnimationOptionCurveEaseInOut
, was in einer fortlaufenden Animation nicht richtig aussieht. Außerdem habe ich ein Häkchen hinzugefügt, damit ich meine Animation bei Bedarf nach einer geraden Vierteldrehung stoppen kann (nicht unendlich, sondern von unendlich Dauer), und Die Beschleunigungsrampe wurde in den ersten 90 Grad angehoben und in den letzten 90 Grad abgebremst (nachdem ein Stopp angefordert wurde):
// an ivar for your class:
BOOL animating;
- (void)spinWithOptions:(UIViewAnimationOptions)options {
// this spin completes 360 degrees every 2 seconds
[UIView animateWithDuration:0.5
delay:0
options:options
animations:^{
self.imageToMove.transform = CGAffineTransformRotate(imageToMove.transform, M_PI / 2);
}
completion:^(BOOL finished) {
if (finished) {
if (animating) {
// if flag still set, keep spinning with constant speed
[self spinWithOptions: UIViewAnimationOptionCurveLinear];
} else if (options != UIViewAnimationOptionCurveEaseOut) {
// one last spin, with deceleration
[self spinWithOptions: UIViewAnimationOptionCurveEaseOut];
}
}
}];
}
- (void)startSpin {
if (!animating) {
animating = YES;
[self spinWithOptions: UIViewAnimationOptionCurveEaseIn];
}
}
- (void)stopSpin {
// set the flag to stop spinning after one last 90 degree increment
animating = NO;
}
Ich habe die Möglichkeit hinzugefügt, Anfragen zu bearbeiten, um erneut mit dem Drehen zu beginnen (startSpin
), während das vorherige Drehen sich abwickelt (abgeschlossen). Beispielprojekt hier auf Github .
In Swift können Sie den folgenden Code für die unendliche Drehung verwenden:
extension UIView {
private static let kRotationAnimationKey = "rotationanimationkey"
func rotate(duration: Double = 1) {
if layer.animation(forKey: UIView.kRotationAnimationKey) == nil {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Float.pi * 2.0
rotationAnimation.duration = duration
rotationAnimation.repeatCount = Float.infinity
layer.add(rotationAnimation, forKey: UIView.kRotationAnimationKey)
}
}
func stopRotating() {
if layer.animation(forKey: UIView.kRotationAnimationKey) != nil {
layer.removeAnimation(forKey: UIView.kRotationAnimationKey)
}
}
}
let kRotationAnimationKey = "com.myapplication.rotationanimationkey" // Any key
func rotateView(view: UIView, duration: Double = 1) {
if view.layer.animationForKey(kRotationAnimationKey) == nil {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Float(M_PI * 2.0)
rotationAnimation.duration = duration
rotationAnimation.repeatCount = Float.infinity
view.layer.addAnimation(rotationAnimation, forKey: kRotationAnimationKey)
}
}
Stoppen ist wie folgt:
func stopRotatingView(view: UIView) {
if view.layer.animationForKey(kRotationAnimationKey) != nil {
view.layer.removeAnimationForKey(kRotationAnimationKey)
}
}
Die obige Antwort von Nate ist ideal zum Stoppen und Starten von Animationen und bietet eine bessere Kontrolle. Ich war neugierig, warum deins nicht funktioniert hat und seins. Ich wollte hier meine Erkenntnisse und eine einfachere Version des Codes veröffentlichen, die eine UIView kontinuierlich animieren würde, ohne anzuhalten.
Dies ist der Code, den ich verwendet habe,
- (void)rotateImageView
{
[UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
[self.imageView setTransform:CGAffineTransformRotate(self.imageView.transform, M_PI_2)];
}completion:^(BOOL finished){
if (finished) {
[self rotateImageView];
}
}];
}
Ich habe 'CGAffineTransformRotate' anstelle von 'CGAffineTransformMakeRotation' verwendet, da ersteres das Ergebnis zurückgibt, das beim Fortschreiten der Animation gespeichert wird. Dies verhindert das Springen oder Zurücksetzen der Ansicht während der Animation.
Eine andere Möglichkeit ist, 'UIViewAnimationOptionRepeat' nicht zu verwenden, da am Ende der Animation, bevor sie wiederholt wird, die Transformation zurückgesetzt wird und die Ansicht an ihre ursprüngliche Position zurückspringt. Anstelle einer Wiederholung wird eine Rekursion durchgeführt, sodass die Transformation nie auf den ursprünglichen Wert zurückgesetzt wird, da der Animationsblock praktisch nie endet.
Und das Letzte ist, dass Sie die Ansicht in 90-Grad-Schritten (M_PI/2) anstatt in 360 oder 180-Grad-Schritten (2 * M_PI oder M_PI) transformieren müssen. Weil die Transformation als Matrixmultiplikation von Sinus- und Cosinuswerten auftritt.
t' = [ cos(angle) sin(angle) -sin(angle) cos(angle) 0 0 ] * t
Wenn Sie also eine 180-Grad-Transformation verwenden, ergibt der Cosinus von 180 den Wert -1, wodurch die Ansicht jedes Mal in die entgegengesetzte Richtung transformiert wird. Bei einer 360-Grad-Transformation wird lediglich die Ansicht angefordert, an der Stelle zu bleiben, an der sie sich befunden hat. Sie sehen also überhaupt keine Drehung.
Wenn Sie das Bild nur endlos drehen möchten, funktioniert dies recht gut und ist sehr einfach:
NSTimeInterval duration = 10.0f;
CGFloat angle = M_PI / 2.0f;
CGAffineTransform rotateTransform = CGAffineTransformRotate(imageView.transform, angle);
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionRepeat| UIViewAnimationOptionCurveLinear animations:^{
imageView.transform = rotateTransform;
} completion:nil];
Nach meiner Erfahrung funktioniert dies einwandfrei, aber stellen Sie sicher, dass Ihr Bild in der Lage ist, ohne Versatz um die Mitte gedreht zu werden. Andernfalls "springt" die Bildanimation, sobald es zu PI gelangt.
Um die Drehrichtung zu ändern, ändern Sie das Vorzeichen von angle
(angle *= -1
).
pdate Die Kommentare von @AlexPretzlav veranlassten mich, das noch einmal zu wiederholen, und ich stellte fest, dass das Bild, das ich drehte, sowohl entlang der vertikalen als auch der horizontalen Achse gespiegelt wurde, was bedeutet, dass sich das Bild tatsächlich nur um 90 Grad drehte und dann Zurücksetzen, obwohl es aussah , als würde es sich weiter drehen.
Wenn Ihr Bild so aussieht wie meins, funktioniert dies hervorragend. Wenn das Bild jedoch nicht symmetrisch ist, stellen Sie fest, dass es nach 90 Grad wieder in der ursprünglichen Ausrichtung einrastet.
Um ein nicht symmetrisches Bild zu drehen, ist die akzeptierte Antwort besser geeignet.
Eine dieser weniger eleganten Lösungen (siehe unten) dreht das Bild tatsächlich. Beim Neustart der Animation kann jedoch ein merkliches Ruckeln auftreten:
- (void)spin
{
NSTimeInterval duration = 0.5f;
CGFloat angle = M_PI_2;
CGAffineTransform rotateTransform = CGAffineTransformRotate(self.imageView.transform, angle);
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
self.imageView.transform = rotateTransform;
} completion:^(BOOL finished) {
[self spin];
}];
}
Sie können dies auch nur mit Blöcken tun, wie @ richard-j-ross-iii vorschlägt, aber Sie erhalten eine Retain-Loop-Warnung, da der Block sich selbst erfasst:
__block void(^spin)() = ^{
NSTimeInterval duration = 0.5f;
CGFloat angle = M_PI_2;
CGAffineTransform rotateTransform = CGAffineTransformRotate(self.imageView.transform, angle);
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
self.imageView.transform = rotateTransform;
} completion:^(BOOL finished) {
spin();
}];
};
spin();
Mein Beitrag mit einer Swift Extension aus der geprüften Lösung:
Swift 4.
extension UIView{
func rotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = NSNumber(value: Double.pi * 2)
rotation.duration = 1
rotation.isCumulative = true
rotation.repeatCount = Float.greatestFiniteMagnitude
self.layer.add(rotation, forKey: "rotationAnimation")
}
}
Veraltet:
extension UIView{
func rotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = NSNumber(double: M_PI * 2)
rotation.duration = 1
rotation.cumulative = true
rotation.repeatCount = FLT_MAX
self.layer.addAnimation(rotation, forKey: "rotationAnimation")
}
}
Verwenden Sie eine Vierteldrehung und erhöhen Sie die Drehung schrittweise.
void (^block)() = ^{
imageToMove.transform = CGAffineTransformRotate(imageToMove.transform, M_PI / 2);
}
void (^completion)(BOOL) = ^(BOOL finished){
[UIView animateWithDuration:1.0
delay:0.0
options:0
animations:block
completion:completion];
}
completion(YES);
David Rysaneks großartige Antwort aktualisiert auf Swift 4:
import UIKit
extension UIView {
func startRotating(duration: CFTimeInterval = 3, repeatCount: Float = Float.infinity, clockwise: Bool = true) {
if self.layer.animation(forKey: "transform.rotation.z") != nil {
return
}
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
let direction = clockwise ? 1.0 : -1.0
animation.toValue = NSNumber(value: .pi * 2 * direction)
animation.duration = duration
animation.isCumulative = true
animation.repeatCount = repeatCount
self.layer.add(animation, forKey:"transform.rotation.z")
}
func stopRotating() {
self.layer.removeAnimation(forKey: "transform.rotation.z")
}
}
}
Das hat bei mir funktioniert:
[UIView animateWithDuration:1.0
animations:^
{
self.imageView.transform = CGAffineTransformMakeRotation(M_PI);
self.imageView.transform = CGAffineTransformMakeRotation(0);
}];
Ich habe Nizza Code in diesem gefunden Repository ,
Hier ist der Code davon Ich habe kleine Änderungen vorgenommen, je nach meinem Bedürfnis nach Geschwindigkeit :)
UIImageView + Rotate.h
#import <Foundation/Foundation.h>
@interface UIImageView (Rotate)
- (void)rotate360WithDuration:(CGFloat)duration repeatCount:(float)repeatCount;
- (void)pauseAnimations;
- (void)resumeAnimations;
- (void)stopAllAnimations;
@end
UIImageView + Rotate.m
#import <QuartzCore/QuartzCore.h>
#import "UIImageView+Rotate.h"
@implementation UIImageView (Rotate)
- (void)rotate360WithDuration:(CGFloat)duration repeatCount:(float)repeatCount
{
CABasicAnimation *fullRotation;
fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
fullRotation.fromValue = [NSNumber numberWithFloat:0];
//fullRotation.toValue = [NSNumber numberWithFloat:(2*M_PI)];
fullRotation.toValue = [NSNumber numberWithFloat:-(2*M_PI)]; // added this minus sign as i want to rotate it to anticlockwise
fullRotation.duration = duration;
fullRotation.speed = 2.0f; // Changed rotation speed
if (repeatCount == 0)
fullRotation.repeatCount = MAXFLOAT;
else
fullRotation.repeatCount = repeatCount;
[self.layer addAnimation:fullRotation forKey:@"360"];
}
//Not using this methods :)
- (void)stopAllAnimations
{
[self.layer removeAllAnimations];
};
- (void)pauseAnimations
{
[self pauseLayer:self.layer];
}
- (void)resumeAnimations
{
[self resumeLayer:self.layer];
}
- (void)pauseLayer:(CALayer *)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
layer.speed = 0.0;
layer.timeOffset = pausedTime;
}
- (void)resumeLayer:(CALayer *)layer
{
CFTimeInterval pausedTime = [layer timeOffset];
layer.speed = 1.0;
layer.timeOffset = 0.0;
layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
layer.beginTime = timeSincePause;
}
@end
Hier ist meine Swift Lösung als UIView-Erweiterung. Sie könnte als Simulation eines UIActivityIndicator-Verhaltens auf jedem UIImageView angesehen werden.
import UIKit
extension UIView
{
/**
Starts rotating the view around Z axis.
@param duration Duration of one full 360 degrees rotation. One second is default.
@param repeatCount How many times the spin should be done. If not provided, the view will spin forever.
@param clockwise Direction of the rotation. Default is clockwise (true).
*/
func startZRotation(duration duration: CFTimeInterval = 1, repeatCount: Float = Float.infinity, clockwise: Bool = true)
{
if self.layer.animationForKey("transform.rotation.z") != nil {
return
}
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
let direction = clockwise ? 1.0 : -1.0
animation.toValue = NSNumber(double: M_PI * 2 * direction)
animation.duration = duration
animation.cumulative = true
animation.repeatCount = repeatCount
self.layer.addAnimation(animation, forKey:"transform.rotation.z")
}
/// Stop rotating the view around Z axis.
func stopZRotation()
{
self.layer.removeAnimationForKey("transform.rotation.z")
}
}
Eine Swift3-Version:
extension UIView {
func startRotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = NSNumber(value: M_PI * 2)
rotation.duration = 2
rotation.isCumulative = true
rotation.repeatCount = FLT_MAX
self.layer.add(rotation, forKey: "rotationAnimation")
}
func stopRotate() {
self.layer.removeAnimation(forKey: "rotationAnimation")
}
}
Und denken Sie daran, startRotate
in viewWillAppear
aufzurufen, nicht in viewDidLoad
.
Es gibt verschiedene Möglichkeiten, eine 360-Grad-Animation mit UIView durchzuführen.
Mit CABasicAnimation
var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
view.layer.add(rotationAnimation, forKey: "rotationAnimation")
Hier ist eine Erweiterungsfunktion für UIView, die das Starten und Stoppen von Rotationsvorgängen übernimmt:
extension UIView {
// Start rotation
func startRotation() {
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = NSNumber(value: Double.pi)
rotation.duration = 1.0
rotation.isCumulative = true
rotation.repeatCount = FLT_MAX
self.layer.add(rotation, forKey: "rotationAnimation")
}
// Stop rotation
func stopRotation() {
self.layer.removeAnimation(forKey: "rotationAnimation")
}
}
Verwenden Sie jetzt IView.animation closure:
UIView.animate(withDuration: 0.5, animations: {
view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi))
}) { (isAnimationComplete) in
// Animation completed
}
Wenn jemand die Lösung von Nates wollte, aber in Swift, dann ist hier eine grobe Swift Übersetzung:
class SomeClass: UIViewController {
var animating : Bool = false
@IBOutlet weak var activityIndicatorImage: UIImageView!
func startSpinning() {
if(!animating) {
animating = true;
spinWithOptions(UIViewAnimationOptions.CurveEaseIn);
}
}
func stopSpinning() {
animating = false
}
func spinWithOptions(options: UIViewAnimationOptions) {
UIView.animateWithDuration(0.5, delay: 0.0, options: options, animations: { () -> Void in
let val : CGFloat = CGFloat((M_PI / Double(2.0)));
self.activityIndicatorImage.transform = CGAffineTransformRotate(self.activityIndicatorImage.transform,val)
}) { (finished: Bool) -> Void in
if(finished) {
if(self.animating){
self.spinWithOptions(UIViewAnimationOptions.CurveLinear)
} else if (options != UIViewAnimationOptions.CurveEaseOut) {
self.spinWithOptions(UIViewAnimationOptions.CurveEaseOut)
}
}
}
}
override func viewDidLoad() {
startSpinning()
}
}
für xamarin ios:
public static void RotateAnimation (this UIView view, float duration=1, float rotations=1, float repeat=int.MaxValue)
{
var rotationAnimation = CABasicAnimation.FromKeyPath ("transform.rotation.z");
rotationAnimation.To = new NSNumber (Math.PI * 2.0 /* full rotation*/ * 1 * 1);
rotationAnimation.Duration = 1;
rotationAnimation.Cumulative = true;
rotationAnimation.RepeatCount = int.MaxValue;
rotationAnimation.RemovedOnCompletion = false;
view.Layer.AddAnimation (rotationAnimation, "rotationAnimation");
}
Sie können dieselbe Art von Animation auch mit UIView und Blöcken ausführen. Hier ist eine Klassenerweiterungsmethode, mit der die Ansicht um einen beliebigen Winkel gedreht werden kann.
- (void)rotationWithDuration:(NSTimeInterval)duration angle:(CGFloat)angle options:(UIViewAnimationOptions)options
{
// Repeat a quarter rotation as many times as needed to complete the full rotation
CGFloat sign = angle > 0 ? 1 : -1;
__block NSUInteger numberRepeats = floorf(fabsf(angle) / M_PI_2);
CGFloat quarterDuration = duration * M_PI_2 / fabs(angle);
CGFloat lastRotation = angle - sign * numberRepeats * M_PI_2;
CGFloat lastDuration = duration - quarterDuration * numberRepeats;
__block UIViewAnimationOptions startOptions = UIViewAnimationOptionBeginFromCurrentState;
UIViewAnimationOptions endOptions = UIViewAnimationOptionBeginFromCurrentState;
if (options & UIViewAnimationOptionCurveEaseIn || options == UIViewAnimationOptionCurveEaseInOut) {
startOptions |= UIViewAnimationOptionCurveEaseIn;
} else {
startOptions |= UIViewAnimationOptionCurveLinear;
}
if (options & UIViewAnimationOptionCurveEaseOut || options == UIViewAnimationOptionCurveEaseInOut) {
endOptions |= UIViewAnimationOptionCurveEaseOut;
} else {
endOptions |= UIViewAnimationOptionCurveLinear;
}
void (^lastRotationBlock)(void) = ^ {
[UIView animateWithDuration:lastDuration
delay:0
options:endOptions
animations:^{
self.transform = CGAffineTransformRotate(self.transform, lastRotation);
}
completion:^(BOOL finished) {
NSLog(@"Animation completed");
}
];
};
if (numberRepeats) {
__block void (^quarterSpinningBlock)(void) = ^{
[UIView animateWithDuration:quarterDuration
delay:0
options:startOptions
animations:^{
self.transform = CGAffineTransformRotate(self.transform, M_PI_2);
numberRepeats--;
}
completion:^(BOOL finished) {
if (numberRepeats > 0) {
startOptions = UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear;
quarterSpinningBlock();
} else {
lastRotationBlock();
}NSLog(@"Animation completed");
}
];
};
quarterSpinningBlock();
} else {
lastRotationBlock();
}
}
Swift 4.
func rotateImageView()
{
UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {() -> Void in
self.imageView.transform = self.imageView.transform.rotated(by: .pi / 2)
}, completion: {(_ finished: Bool) -> Void in
if finished {
rotateImageView()
}
})
}
@ Ram Antwort war wirklich hilfreich. Hier ist eine Swift Version der Antwort.
Swift 2
private func rotateImageView() {
UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, CGFloat(M_PI_2))
}) { (finished) -> Void in
if finished {
self.rotateImageView()
}
}
}
Swift 3,4,5
private func rotateImageView() {
UIView.animate(withDuration: 1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: { () -> Void in
self.imageView.transform = self.imageView.transform.rotated(by: .pi / 2)
}) { (finished) -> Void in
if finished {
self.rotateImageView()
}
}
}
Erstellen Sie die Animation
- (CABasicAnimation *)spinAnimationWithDuration:(CGFloat)duration clockwise:(BOOL)clockwise repeat:(BOOL)repeats
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
anim.toValue = clockwise ? @(M_PI * 2.0) : @(M_PI * -2.0);
anim.duration = duration;
anim.cumulative = YES;
anim.repeatCount = repeats ? CGFLOAT_MAX : 0;
return anim;
}
Fügen Sie es einer Ansicht wie dieser hinzu
CABasicAnimation *animation = [self spinAnimationWithDuration:1.0 clockwise:YES repeat:YES];
[self.spinningView.layer addAnimation:animation forKey:@"rotationAnimation"];
Wie unterscheidet sich diese Antwort? Sie werden viel saubereren Code haben, wenn die meisten Ihrer Funktionen Objekte zurückgeben, anstatt nur einige Objekte hier und da zu manipulieren.
So drehe ich 360 in die richtige Richtung.
[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionRepeat|UIViewAnimationOptionCurveLinear
animations:^{
[imageIndView setTransform:CGAffineTransformRotate([imageIndView transform], M_PI-0.00001f)];
} completion:nil];
Ich habe ein glänzendes Animations-Framework entwickelt, mit dem Sie viel Zeit sparen können! Damit kann diese Animation sehr einfach erstellt werden:
private var endlessRotater: EndlessAnimator!
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
let rotationAnimation = AdditiveRotateAnimator(M_PI).to(targetView).duration(2.0).baseAnimation(.CurveLinear)
endlessRotater = EndlessAnimator(rotationAnimation)
endlessRotater.animate()
}
um diese Animation zu stoppen, setzen Sie einfach nil
auf endlessRotater
.
Wenn Sie interessiert sind, schauen Sie bitte vorbei: https://github.com/hip4yes/Animatics
Swift 4 ,
func rotateImage(image: UIImageView) {
UIView.animate(withDuration: 1, animations: {
image.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
image.transform = CGAffineTransform.identity
}) { (completed) in
self.rotateImage()
}
}
Swift 3:
var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (M_PI * 2.0))
rotationAnimation.duration = 2.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 10.0
view.layer.add(rotationAnimation, forKey: "rotationAnimation")
Swift:
func runSpinAnimationOnView(view:UIView , duration:Float, rotations:Double, repeatt:Float ) ->()
{
let rotationAnimation=CABasicAnimation();
rotationAnimation.keyPath="transform.rotation.z"
let toValue = M_PI * 2.0 * rotations ;
// passing it a float
let someInterval = CFTimeInterval(duration)
rotationAnimation.toValue=toValue;
rotationAnimation.duration=someInterval;
rotationAnimation.cumulative=true;
rotationAnimation.repeatCount=repeatt;
view.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
}
let val = CGFloat(M_PI_2)
UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .curveLinear], animations: {
self.viewToRotate.transform = self.viewToRotate.transform.rotated(by: val)
})