返回

中秋月圆之夜,嫦娥奔月技术之旅

IOS

中秋佳节,皓月当空,不禁让人联想到嫦娥奔月的传奇故事。作为一名技术博主,我们自然要借助技术的力量,重现这一神话传说。本文将使用 Quartz2D、粒子动画和 CoreAnimation 三种技术,打造一个简约版嫦娥奔月的动画效果。

Quartz2D 绘制月景

首先,我们使用 Quartz2D 来绘制月景。创建一个新的 UIView,将其作为画布,然后使用 Core Graphics API 来绘制圆形月亮和广寒宫。代码如下:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    // 绘制月亮
    CGContextAddEllipseInRect(context, CGRectMake(0, 0, 100, 100));
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillPath(context);

    // 绘制广寒宫
    CGContextMoveToPoint(context, 25, 25);
    CGContextAddLineToPoint(context, 75, 25);
    CGContextAddLineToPoint(context, 75, 75);
    CGContextAddLineToPoint(context, 25, 75);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 2.0);
    CGContextStrokePath(context);
}

粒子动画模拟嫦娥

接下来,我们使用粒子动画来模拟嫦娥飞奔的样子。创建另一个 UIView,作为粒子动画的容器,并使用 CAEmitterLayer 来生成粒子。代码如下:

- (void)startParticleAnimation {
    CAEmitterLayer *emitter = [CAEmitterLayer layer];
    emitter.emitterShape = kCAEmitterLayerLine;
    emitter.emitterPosition = CGPointMake(50, 0);
    emitter.emitterSize = CGSizeMake(100, 0);
    emitter.renderMode = kCAEmitterLayerAdditive;

    CAEmitterCell *cell = [CAEmitterCell emitterCell];
    cell.contents = (__bridge id _Nullable)([UIImage imageNamed:@"changa"].CGImage);
    cell.birthRate = 100;
    cell.lifetime = 3;
    cell.velocity = 500;
    cell.velocityRange = 100;
    cell.emissionRange = M_PI;

    emitter.emitterCells = @[cell];
    [self.view.layer addSublayer:emitter];
}

CoreAnimation 实现背景移动

最后,我们使用 CoreAnimation 来实现背景的移动效果,营造嫦娥奔月的动态感。创建第三个 UIView,作为背景,并使用 CAKeyframeAnimation 来控制其位置。代码如下:

- (void)startBackgroundAnimation {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.values = @[@(CGPointMake(0, 0)), @(CGPointMake(-100, 0))];
    animation.duration = 3;
    animation.repeatCount = MAXFLOAT;
    [self.view.layer addAnimation:animation forKey:@"backgroundAnimation"];
}