Core Animation - modify animation property

后端 未结 3 931
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 13:47

I have animation

 func startRotate360() {
    let rotation : CABasicAnimation = CABasicAnimation(keyPath: \"transform.rotation.z\")
    rotation.fromValue =          


        
3条回答
  •  太阳男子
    2020-12-21 14:23

    2019 typical modern syntax

    Setup the arc and the layer like this:

    import Foundation
    import UIKit
    
    class RoundChaser: UIView {
        
        private let lineThick: CGFloat = 10.0
        private let beginFraction: CGFloat = 0.15
        // where does the arc drawing begin?
        // 0==top, .25==right, .5==bottom, .75==left
        
        private lazy var arcPath: CGPath = {
            let b = beginFraction * .pi * 2.0
            return UIBezierPath(
                arcCenter: bounds.centerOfCGRect(),
                radius: bounds.width / 2.0 - lineThick / 2.0,
                startAngle: .pi * -0.5 + b,
                // recall that .pi * -0.5 is the "top"
                endAngle: .pi * 1.5 + b,
                clockwise: true
            ).cgPath
        }()
        
        private lazy var arcLayer: CAShapeLayer = {
            let l = CAShapeLayer()
            l.path = arcPath
            l.fillColor = UIColor.clear.cgColor
            l.strokeColor = UIColor.purple.cgColor
            l.lineWidth = lineThick
            l.lineCap = CAShapeLayerLineCap.round
            l.strokeStart = 0
            l.strokeEnd = 0
            // if both are same, it is hidden. initially hidden
            layer.addSublayer(l)
            return l
        }()
        
    

    then initialization is this easy

        open override func layoutSubviews() {
            super.layoutSubviews()
            arcLayer.frame = bounds
        }
        
    

    finally animation is easy

        public func begin() {
            CATransaction.begin()
            
            let e : CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
            e.duration = 2.0
            e.fromValue = 0
            e.toValue = 1.0
            // recall 0 will be our beginFraction, see above
            e.repeatCount = .greatestFiniteMagnitude
            
            self.arcLayer.add(e, forKey: nil)
            CATransaction.commit()
        }
    }
    

提交回复
热议问题