以下代码适用于我。它实际上并没有改变方向。我认为您可以通过添加一个更改 imagesArray 的计时器来实现这一点。首先,我也尝试像您一样使用 CAKeyframeAnimation,但我无法弄清楚。所以我改用动画图像 - 我认为这种方式不会太糟糕,因为 Apple 例如也使用这种方式来为活动指示器设置动画。
-(void) myImageInitFunction {
UIImage *icon = [UIImage imageNamed:@"yourIconImage"];
NSArray *imagesArray = rotatingImagesArrayOfImage(icon, 30);
myImageViewThatShouldRotate.animationImages = imageArray;
myImageViewThatShouldRotate.animationDuration= 2.0;
[myImageViewThatShouldRotate startAnimating];
}
NSArray *rotatingImagesArrayOfImage(UIImage * icon, NSInteger nFrames)
{
NSMutableArray *images = [NSMutableArray arrayWithObject:icon];
for (NSInteger nLoop = 1; nLoop < nFrames; nLoop++) {
[images addObject: [UIImage imageWithCGImage: CGImageRotatedByAngle(icon.CGImage, nLoop * ( 360 / nFrames)) ] ];
}
return images;
}
CGImageRef CGImageRotatedByAngle(CGImageRef imgRef, CGFloat angle) {
CGFloat angleInRadians = angle * (M_PI / 180);
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGRect imgRect = CGRectMake(0, 0, width, height);
CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians);
CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL,
rotatedRect.size.width,
rotatedRect.size.height,
8,
0,
colorSpace,
kCGImageAlphaPremultipliedFirst);
CGContextSetAllowsAntialiasing(bmContext, YES);
CGContextSetShouldAntialias(bmContext, YES);
CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);
CGColorSpaceRelease(colorSpace);
CGContextTranslateCTM(bmContext,
+(rotatedRect.size.width/2),
+(rotatedRect.size.height/2));
CGContextRotateCTM(bmContext, angleInRadians);
CGContextTranslateCTM(bmContext,
-(rotatedRect.size.width/2),
-(rotatedRect.size.height/2));
CGContextDrawImage(bmContext, CGRectMake(0, 0,
rotatedRect.size.width,
rotatedRect.size.height),
imgRef);
CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
CFRelease(bmContext);
return rotatedImage;
}