ios - 如何在IOS中制作月亮绕地球旋转同时自己旋转的CAAnimation效果?

标签 ios calayer caanimation anchorpoint

我知道在IOS中制作月亮绕地球转的效果很简单。假设月亮是一个 CALayer 对象,只需将这个对象的 anchorPoint 改为地球,它就会围绕地球旋转。但是如何创造同时自转的月亮呢?由于月亮只能有一个 anchor ,看来我不能再让这个 CALayer 对象自行旋转了。你们有什么感想?谢谢。

最佳答案

您可以通过沿着贝塞尔曲线路径设置“月亮”的动画来使“月亮”围绕一个点旋转,同时设置旋转变换的动画。这是一个简单的例子,

@interface ViewController ()
@property (strong,nonatomic) UIButton *moon;
@property (strong,nonatomic) UIBezierPath *circlePath;
@end

@implementation ViewController

-(void)viewDidLoad {
    self.moon = [UIButton buttonWithType:UIButtonTypeInfoDark];
    [self.moon addTarget:self action:@selector(clickedCircleButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.moon];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    CGRect circleRect = CGRectMake(60,100,200,200);
     self.circlePath = [UIBezierPath bezierPathWithOvalInRect:circleRect];
     self.moon.center = CGPointMake(circleRect.origin.x + circleRect.size.width, circleRect.origin.y + circleRect.size.height/2.0);
}

- (void)clickedCircleButton:(UIButton *)sender {

    CAKeyframeAnimation *orbit = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    orbit.path = self.circlePath.CGPath;
    orbit.calculationMode = kCAAnimationPaced;
    orbit.duration = 4.0;
    orbit.repeatCount = CGFLOAT_MAX;
    [self.moon.layer addAnimation:orbit forKey:@"circleAnimation"];

    CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    fullRotation.fromValue = 0;
    fullRotation.byValue   = @(2.0*M_PI);
    fullRotation.duration = 4.0;
    fullRotation.repeatCount = CGFLOAT_MAX;
    [self.moon.layer addAnimation:fullRotation forKey:@"Rotate"];
}

这些特定值将导致“月亮”像地球的月亮一样保持朝向中心的同一面。

关于ios - 如何在IOS中制作月亮绕地球旋转同时自己旋转的CAAnimation效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399892/

相关文章:

ios - 如何从 AVCaptureVideoPreviewLayer 获取 UIImage?

ios - CALayer 子类不对属性更改进行动画处理

iphone:如何进行翻页

objective-c - 使用 fadeIn/fadeOut CABasicAnimation 的闪烁效果

ios - 个人 pem 文件和标准 pem 文件有什么区别?

ios - 特殊字符串格式的 ObjC 注册应用程序

objective-c - 在 UISplitView 中更改 RootViewController 的颜色

ios - Admob 自家广告未显示在我的 iPhone 设备中

iOS:CALayer 的辅助功能标签

ios - CALayer removeAnimationForKey : throws CABasicAnimation length: unrecognized selector sent to instance