【问题标题】:Animate sublayers of a layer动画层的子层
【发布时间】:2020-08-17 17:39:54
【问题描述】:

我有一个绘制 2 层的视图;

  • 一行
  • 渐变

现在,当我切换路径时,我想同时为两个图层设置动画。所以要做到这一点,我首先有 2 个单独的图层,并为每个图层添加了一个动画。那行得通,但我不喜欢我必须为每个人编写动画的事实。

这就是为什么我决定创建一个 CAShapeLayer 子类并将渐变移动到线条层中,因此在层次结构方面它看起来像这样;

  • 一条线
    • 渐变

在代码中;

class LineLayer: CAShapeLayer {
    // Configuration
    private var configuration: ChartConfiguration!

    // Layers
    private var backgroundLayer: CAGradientLayer!

    init(configuration: ChartConfiguration) {
        super.init()
        self.configuration = configuration
        configureLayers()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func configureLayers() {
        addLineLayer()
        addBackgroundLayer()
    }

    private func addLineLayer() {
        self.fillColor = UIColor.clear.cgColor
        self.strokeColor = configuration.lineColor
        self.lineWidth = configuration.lineWidth
    }

    private func addBackgroundLayer() {
        backgroundLayer = CAGradientLayer()
        backgroundLayer.anchorPoint = CGPoint(x: 0, y: 0)
        backgroundLayer.colors = [UIColor.systemGreen.withAlphaComponent(0.24).cgColor, UIColor.systemGreen.withAlphaComponent(0).cgColor]
        backgroundLayer.startPoint = CGPoint(x: 0, y: 0)
        backgroundLayer.endPoint = CGPoint(x: 0, y: 1)
        self.addSublayer(backgroundLayer)
    }

    public func updateBackgroundLayer(frame: CGRect, mask: CAShapeLayer) {
        backgroundLayer.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        backgroundLayer.mask = mask
    }
}

然后我为父级(线条)设置动画,并认为子级(渐变)会随之移动。不幸的是,这不会发生。我的动画代码是这样的;

    lineLayer = LineLayer(configuration: configuration)
    lineLayer.path = linePath
    self.layer.addSublayer(lineLayer)

    private func addPathAnimation() {
        let animation = CABasicAnimation(keyPath: "path")
        animation.duration = configuration.animationDuration
        animation.fromValue = layer.path != nil ? layer.path : linePath
        animation.toValue = path
        animation.timingFunction = configuration.animationCurve
        layer.add(animation, forKey: nil)
        layer.path = path
    }

只为父级设置动画时是否可以为子级设置动画?还是我只需要坚持添加到视图中的单独图层并为每个图层设置动画?

【问题讨论】:

    标签: swift animation calayer cashapelayer cabasicanimation


    【解决方案1】:

    只为父级设置动画时是否可以为子级设置动画?

    是的(如果我正确理解了这个问题)。你add给父一个CAAnimationGroup。该组协调多个子 CAAnimations。假设这些是某种属性动画,每个子动画的 keyPath 可以是父动画的属性或其任何子子图层的属性(使用符号 "sublayers.name.property",其中 name 是孩子的name 属性)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多