【问题标题】:Add glow effect to text of a UI button - swift为 UI 按钮的文本添加发光效果 - swift
【发布时间】:2019-12-08 16:38:47
【问题描述】:

我的问题很直接。我的目标是快速为按钮添加基本的发光效果。我希望文本发光,而不是整个按钮框。 我附上了一张图片作为示例来说明我的目标。

我曾在其他地方寻找过,但通常只能找到我不想要的动画。抱歉,图片质量很差。

我目前正在使用此代码,但我的设置按钮出现的光很弱,我怎样才能使它更强大:

import UIKit

extension UIView {
    enum GlowEffect: Float {
        case small = 0.4, normal = 2, big = 30
    }

    func doGlowAnimation(withColor color: UIColor, withEffect effect: GlowEffect = .normal) {
        layer.masksToBounds = false
        layer.shadowColor = color.cgColor
        layer.shadowRadius = 0
        layer.shadowOpacity = 1
        layer.shadowOffset = .zero

        let glowAnimation = CABasicAnimation(keyPath: "shadowRadius")
        glowAnimation.fromValue = 20 // effect.rawValue
        glowAnimation.toValue = 20
        glowAnimation.fillMode = .removed
        glowAnimation.repeatCount = .infinity
        layer.add(glowAnimation, forKey: "shadowGlowingAnimation")
    }
}

改变强度不会在单个字母附近产生强烈的色彩效果

【问题讨论】:

    标签: swift button glow


    【解决方案1】:

    要在UIButton 的标题上创建外发光效果,您需要确保调整UIButtontitleLabel 的阴影属性。这意味着您可以通过以下方式运行动画:

    button.titleLabel?.doGlowAnimation(withColor: UIColor.yellow)
    

    动画调整 shadowRadius 虽然当前从 20 变为 20 所以没有实际的动画。

    extension UIView {
        enum GlowEffect: Float {
            case small = 0.4, normal = 2, big = 30
        }
    
        func doGlowAnimation(withColor color: UIColor, withEffect effect: GlowEffect = .normal) {
            layer.masksToBounds = false
            layer.shadowColor = color.cgColor
            layer.shadowRadius = 0
            layer.shadowOpacity = 0.8
            layer.shadowOffset = .zero
    
            let glowAnimation = CABasicAnimation(keyPath: "shadowRadius")
            glowAnimation.fromValue = 0
            glowAnimation.toValue = effect.rawValue
            glowAnimation.fillMode = .removed
            glowAnimation.repeatCount = .infinity
            glowAnimation.duration = 2
            glowAnimation.autoreverses = true
            layer.add(glowAnimation, forKey: "shadowGlowingAnimation")
        }
    }
    

    提供脉动的外发光,在两秒内增长然后反转。

    【讨论】: