Анимация CALayer границы альфа - PullRequest
0 голосов
/ 09 июня 2018

У меня есть UIView с рамкой (цвет: зеленый, ширина: 10).

Я пытаюсь анимировать альфа границы (в цикле) от значения 1,0 до значения0,2 - затем обратно к 1,0 - затем обратно к 0,2 и т. д. *

Но CALayer не имеет свойства borderAlpha, поэтому я не уверен, как мне это сделать.

Я пробовал этот код, но он не работал:

UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .autoreverse], animations: {
    self.layer.borderColor = UIColor(cgColor: self.layer.borderColor!).withAlphaComponent(0.2).cgColor
}, completion: nil)

Кто-нибудь знает, как я могу это сделать?

Спасибо!

Ответы [ 2 ]

0 голосов
/ 09 июня 2018

Попробуйте использовать это

class animateStack: UIViewController {

    @IBOutlet weak var animateView: UIView!{
        didSet{
            animateView.layer.borderColor = UIColor.black.cgColor
            animateView.layer.borderWidth = 10
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        animateBorderAlpha()
    }

    private func animateBorderAlpha(){
        /// First Animation
        let animation = CABasicAnimation(keyPath: "borderColor")
        animation.beginTime = 0
        animation.toValue = UIColor.black.withAlphaComponent(0.1).cgColor
        animation.fromValue = UIColor.black.cgColor
        animation.duration = 2

        /// Second Animation
        let animation1 = CABasicAnimation(keyPath: "borderColor")
        animation1.toValue = UIColor.black.cgColor
        animation1.fromValue = UIColor.black.withAlphaComponent(0.1).cgColor
        animation1.beginTime = animation.beginTime + animation.duration
        animation.duration = 4

        /// Animation Group
        let borderColorAnimation: CAAnimationGroup = CAAnimationGroup()
        borderColorAnimation.animations = [animation, animation1]
        borderColorAnimation.duration = animation.duration + animation1.duration
        borderColorAnimation.repeatCount = Float.greatestFiniteMagnitude
        self.animateView.layer.add(borderColorAnimation, forKey: "borderColor")
    }

}

Обновление

class animateViewClass: NSObject {
    class func animateBorderAlpha(_ view: UIView){
        /// First Animation
        let animation = CABasicAnimation(keyPath: "borderColor")
        animation.beginTime = 0
        animation.toValue = UIColor.black.withAlphaComponent(0.1).cgColor
        animation.fromValue = UIColor.black.cgColor
        animation.duration = 2

        /// Second Animation
        let animation1 = CABasicAnimation(keyPath: "borderColor")
        animation1.toValue = UIColor.black.cgColor
        animation1.fromValue = UIColor.black.withAlphaComponent(0.1).cgColor
        animation1.beginTime = animation.beginTime + animation.duration
        animation.duration = 4

        /// Animation Group
        let borderColorAnimation: CAAnimationGroup = CAAnimationGroup()
        borderColorAnimation.animations = [animation, animation1]
        borderColorAnimation.duration = animation.duration + animation1.duration
        borderColorAnimation.repeatCount = Float.greatestFiniteMagnitude
        view.layer.add(borderColorAnimation, forKey: "borderColor")
    }
}

Использование

    animateViewClass.animateBorderAlpha(viewName)
    /// Case of Subclass UIView
    animateViewClass.animateBorderAlpha(self)
0 голосов
/ 09 июня 2018

Обновлен и упрощен .Используйте CALayer для создания пограничного слоя, затем используйте CABasicAnimation для достижения эффекта постепенного исчезновения:

class BorderView: UIView {
    private var boarderLayer:CALayer?
    private let animationKey = "opacityAnimation"

    override public var frame: CGRect {
        didSet{
            self.updateBorder()
        }
    }

    func updateBorder() {
        if boarderLayer == nil {
            boarderLayer = CALayer()
            boarderLayer?.borderColor = UIColor.red.cgColor
            boarderLayer?.borderWidth = 5.0
            self.layer.addSublayer(boarderLayer!)
        }

        boarderLayer?.frame = self.bounds

        if (boarderLayer?.animation(forKey: animationKey) == nil) {
            self.addAnimiation(layer: boarderLayer!,increasing:true)
        }
    }

    func addAnimiation(layer:CALayer,increasing:Bool) {
        CATransaction.begin()

        CATransaction.setCompletionBlock{ [weak self] in
            self?.addAnimiation(layer: layer,increasing:!increasing)
        }

        let animation = CABasicAnimation(keyPath: "opacity")
        if increasing {
            layer.opacity = 0.2
            animation.fromValue = 1.0
            animation.toValue = 0.2
        }
        else{
            layer.opacity = 1.0
            animation.fromValue = 0.2
            animation.toValue = 1.0
        }
        animation.duration = 1.0
        layer.add(animation, forKey: animationKey)

        CATransaction.commit()
    }
}

И результат:

...