Swift文字高亮显示

效果图:

Swift文字高亮显示_第1张图片
highlight.gif

实现思路:

主要通过CAGradientLayer,实现渐变,然后将这个渐变图层添加到View上,通过添加基本动画,不行的改变渐变layer的位置,最终形成文字高亮的显示效果。

代码实现

创建一个UIView的分类,在分类中提供方法以方便在外部调用:

extension UIView {

func startPreviewLoading() {
    layer.masksToBounds = true
    let bgColor = UIColor.lightGray
    let duration: TimeInterval = 1.5
    backgroundColor = bgColor
    
    let gradienLayer = CAGradientLayer()
    gradienLayer.frame = CGRect(x: 0, y: 0, width: kShadowWidth, height: self.frame.size.height)
    gradienLayer.colors = [ bgColor.withAlphaComponent(0.1).cgColor,
                            UIColor.white.withAlphaComponent(0.25).cgColor,
                            UIColor.white.withAlphaComponent(0.4).cgColor,
                            UIColor.white.withAlphaComponent(0.25).cgColor,
                            bgColor.withAlphaComponent(0.1).cgColor
    ]
    gradienLayer.startPoint = CGPoint(x: 0, y: 0.5)
    gradienLayer.endPoint = CGPoint(x: 1, y: 0.5)
    layer.addSublayer(gradienLayer)
    
    func animate() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.fromValue = NSValue(cgPoint: CGPoint(x: -kShadowWidth / 2.0, y: self.frame.size.height / 2.0))
        animation.toValue = NSValue(cgPoint: CGPoint(x: self.frame.size.width + kShadowWidth / 2.0, y: self.frame.size.height / 2.0))
        animation.duration = duration
        animation.repeatCount = MAXFLOAT
        gradienLayer.add(animation, forKey: "position")
    }
    
    animate()
    
}
}

你可能感兴趣的:(Swift文字高亮显示)