iOS 一个简单的核心动画 (一)

Untitled.gif

相关知识点

CAShapeLayer是CALayer的子类
主要通过 UIBezierPath 来描述图层展现效果
在实际应用中,与核心动画联用实现形状动画非常方便

代码

    /// 实例化一个CAShapeLayer对象
    CAShapeLayer *layer = [CAShapeLayer layer];
    /// 设置图层属性
    /// 设置开始路径
    CGFloat radius = 100;
    CGRect rect = CGRectMake(self.view.center.x - radius * 0.5, self.view.center.y - radius * 0.5, radius, radius);
    UIBezierPath *beginPath = [UIBezierPath bezierPathWithOvalInRect:rect];
    layer.path = beginPath.CGPath;

    /// 设置开始路径
    /// 这里用的是勾股定理,取屏幕长宽的平方,再开方
    CGFloat maxRadius = sqrt(kScreenWidth * kScreenWidth + kScreenHeight * kScreenHeight);
    /// 结束位置 - 利用缩进,参数为负,是放大矩形,中心点保持不变
    CGRect endRect = CGRectInset(rect, - maxRadius, - maxRadius);
    UIBezierPath *endPath = [UIBezierPath bezierPathWithOvalInRect:endRect];
    layer.path = endPath.CGPath;

    /// 置图层的遮罩 - 会裁切视图,视图本质上没有发生任何的变化,但是只会显示路径包含范围内的内容
    /// 提示:一旦设置为 mask 属性,填充颜色无效!
    self.view.layer.mask = layer;


    /// 实例化动画对象
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"path"];
    /// 设置动画属性 - 时长/fromValue / toValue
    anim.duration = 3;
    anim.fromValue = (__bridge id _Nullable)(beginPath.CGPath);
    anim.toValue = (__bridge id _Nullable)(endPath.CGPath);
    /// 设置向前填充模式,注意:这个属性如果如果不设置动画会还原
    anim.fillMode = kCAFillModeForwards;
    /// 完成之后不删除,注意:这个属性如果如果不设置动画会还原
    anim.removedOnCompletion = NO;
    /// 将动画添加到图层 - ShaperLayer,让哪个图层动画,就应该将动画添加到哪个图层
    [layer addAnimation:anim forKey:nil];

你可能感兴趣的:(iOS 一个简单的核心动画 (一))