Swift文字高亮显示

效果图:

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()
    
}
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容