需要围绕按钮发光动画

时间:2017-06-30 15:29:44

标签: ios iphone swift uibutton

在我的应用程序中,我有一个大按钮。我希望它周围有一个发光的效果。 可以使用动画完成吗? 我尝试过使用图像,但看起来不干净且吸引人。

1 个答案:

答案 0 :(得分:10)

我一直在处理您的问题,这是我的结果,我定义了UIButton的自定义子类,添加了CABasicAnimation动画shadowRadius属性,将autoreverses设置为是,repeatCount到无穷大

<强> 代码

//
//  GlowingButton.swift
//  NavigationButtonRotateQuestion
//
//  Created by Reinier Melian on 01/07/2017.
//  Copyright © 2017 Pruebas. All rights reserved.
//

import UIKit

@IBDesignable
class GlowingButton: UIButton {

    @IBInspectable var animDuration : CGFloat = 3
    @IBInspectable var cornerRadius : CGFloat = 5
    @IBInspectable var maxGlowSize : CGFloat = 10
    @IBInspectable var minGlowSize : CGFloat = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentScaleFactor = UIScreen.main.scale
        self.layer.masksToBounds = false
        self.setupButton()
        self.startAnimation()
    }

    func setupButton()
    {
        self.layer.cornerRadius = cornerRadius
        self.layer.shadowPath = CGPath(roundedRect: self.bounds, cornerWidth: cornerRadius, cornerHeight: cornerRadius, transform: nil)
        self.layer.shadowColor = UIColor.red.cgColor
        self.layer.shadowOffset = CGSize.zero
        self.layer.shadowRadius = maxGlowSize
        self.layer.shadowOpacity = 1
    }

    func startAnimation()
    {
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = maxGlowSize
        layerAnimation.toValue = minGlowSize
        layerAnimation.autoreverses = true
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        layerAnimation.repeatCount = .infinity
        self.layer.add(layerAnimation, forKey: "glowingAnimation")

    }

}

enter image description here

已修改:已添加Inspectable属性以便更好地进行自定义

希望这有帮助