首页 > 解决方案 > 用动画快速改变圆形边框颜色

问题描述

我使用swift创建了一个圆形按钮,我想做的是用动画改变边框颜色

我使用了以下代码:

let color = CABasicAnimation(keyPath: "borderColor")
color.fromValue = UIColor.black.cgColor
color.toValue = UIColor.red.cgColor
color.duration = 1
color.repeatCount = 1
sender.layer.add(color, forKey: "color and width")

边框颜色正在改变,但它没有得到想要的效果,它一次改变了边框颜色。我想要的效果就像您在旧颜色上绘制一样,为了保持简单 ==> 就像一个进度条,您可以看到旧颜色消失并被新颜色取代。

有什么办法吗?

感谢您的帮助。

更新代码

var storkeLayer = CAShapeLayer()

@IBOutlet weak var Mybut: UIButton!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    storkeLayer.fillColor = UIColor.clear.cgColor
    storkeLayer.strokeColor = UIColor.black.cgColor
    storkeLayer.lineWidth = 2

    // Create a rounded rect path using button's bounds.

    storkeLayer.path = CGPath.init(roundedRect: Mybut.bounds, cornerWidth: Mybut.frame.width / 2 , cornerHeight: Mybut.frame.height / 2, transform: nil)


    // Add layer to the button
    Mybut.layer.addSublayer(storkeLayer)
}


 @IBAction func bytton(_ sender: UIButton) {

    storkeLayer.fillColor = UIColor.clear.cgColor
    storkeLayer.strokeColor = UIColor.red.cgColor
    storkeLayer.lineWidth = 2

    // Create a rounded rect path using button's bounds.

    storkeLayer.path = CGPath.init(roundedRect: Mybut.bounds, cornerWidth: Mybut.frame.width / 2 , cornerHeight: Mybut.frame.height / 2, transform: nil)


    // Add layer to the button
    sender.layer.addSublayer(storkeLayer)

    // Create animation layer and add it to the stroke layer.
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = CGFloat(0.0)
    animation.toValue = CGFloat(1.0)
    animation.duration = 1
   animation.fillMode = kCAFillModeForwards

   // animation.fillMode = kCAFillModeBackwards
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    storkeLayer.add(animation, forKey: "circleAnimation")



}

标签: iosswiftuibuttoncaanimation

解决方案


您可以使用以下代码片段来描边按钮的路径。

@IBAction func buttonTapped(_ sender: UIButton) {
    let storkeLayer = CAShapeLayer()
    storkeLayer.fillColor = UIColor.clear.cgColor
    storkeLayer.strokeColor = UIColor.red.cgColor
    storkeLayer.lineWidth = 2

    // Create a rounded rect path using button's bounds.
    storkeLayer.path = CGPath.init(roundedRect: sender.bounds, cornerWidth: 5, cornerHeight: 5, transform: nil) // same path like the empty one ...
    // Add layer to the button
    sender.layer.addSublayer(storkeLayer)

    // Create animation layer and add it to the stroke layer.
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = CGFloat(0.0)
    animation.toValue = CGFloat(1.0)
    animation.duration = 1
    animation.fillMode = kCAFillModeForwards
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    storkeLayer.add(animation, forKey: "circleAnimation")
}

此代码段创建如下内容:

在此处输入图像描述


推荐阅读