iOS使用CADisplayLink详解,NSMutableAttributedString来实现文字淡入淡出效果

什么是CADisplayLink?

苹果官方文档中对CADisplayLink的描述如下:

A CADisplayLink object is a timer object that allows your application to synchronize its drawing to the refresh rate of the display.

由此我们可以知道, CADisplaylink本质上就是一个能让我们,以和屏幕刷新率相同的频率,将内容画到屏幕上的定时器。也就是说,系统在每次刷新屏幕时都会触发CADisplayLink事件。

开发过程中常用的类似定时器功能又三个:GCD,Timer,CADisplayLink,此处不再扩展,有兴趣可以查看相关文章学习一下,或者留言讨论。

CADisplayLink的基本使用

mkDisplayLink = CADisplayLink.init(target: self, selector: #selector(MKLabel.updateLabelDisplay))

mkDisplayLink?.add(to: .current, forMode: .commonModes)

mkDisplayLink?.isPaused = true

通过以上代码可以知道,CADisplayLink的实现需要添加一个target和selector,target就是要响应的实例对象,selector则是要响应的具体方法。然后将CADisplayLink实例对象添加到Runloop中,这样屏幕刷新时就会回调selector方法。你也可以通过isPaused等于true或false控制对selector的调用。另外CADisplayLink还有属性duration、frameInterval 和 timestamp分别用来获取当前屏幕的刷新时间间隔,两次调用selector之间屏幕刷新次数间隔,以及上一次执行selector的时间戳。

如果不再需要CADisplayLink时,可以通过invalidate进行释放(类似Timer)。

mkDisplayLink?.invalidate()

重点来了,如何利用CADisplayLink的这些特性,实现文字的动态显示效果呢?

先看效果

同时可以响应点击事件以及自定义高亮话题等功能

直接上代码:

首先,对动画进行一些基本数据的设置,开始时间,结束时间,显示的类型(库支持的扩展效果类型)等一些需求属性

func beginFadeAnimation(isFadeIn fadeIn: Bool, displayType: MKLabelDisplayType = .normal, completionBlock: @escaping completionBlock) {

        self.displayType = displayType

        self.completion = completionBlock

        self.isFadeIn = fadeIn

        self.beginTime = CACurrentMediaTime()

        self.endTime = self.beginTime! + self.durationTime

        self.mkDisplayLink?.isPaused = false

        self.setAttributedTextString(NSAttributedString(string:self.text!))

    }


其次,根据设置的属性计算出每个文字在动画过程中显示的时间点以及显示的时长。

    func setAttributedTextString(_ attributedText: NSAttributedString) {

        self.attributedTextString = self.setAlphaAttributedTextString(attributedText) as? NSMutableAttributedString

        var delayTime = 0.0, animationDuration = 0.0

        let totalLength = attributedText.length

        if delayTimeArray.count > 0 {

            delayTimeArray.removeAll()

            animationTimeArray.removeAll()

        }

        for index in 0..<totalLength {

            switch self.displayType {

            case .normal:

                delayTime = Double(arc4random_uniform(UInt32(durationTime/2.0 * 100)))/100.0

                let animationTime = durationTime - delayTime

                animationDuration = (Double(arc4random_uniform(UInt32(animationTime * 100)))/100.0)

            case .ascend:

                delayTime = Double((durationTime * Double(index))/Double(totalLength))

                let animationTime = durationTime - delayTime

                animationDuration = animationTime

                if self.isFadeIn == false {

                    if animationTime > delayTime{

                        animationDuration = delayTime

                    }

                }

            case .descend:

                delayTime = Double((durationTime * Double(index))/Double(totalLength))

                let animationTime = durationTime - delayTime

                animationDuration = animationTime

                if self.isFadeIn == false {

                    if animationTime > delayTime{

                        animationDuration = delayTime

                    }

                }

            case .middle:

                delayTime = Double((durationTime * Double(index))/Double(totalLength))

                let animationTime = durationTime - delayTime

                animationDuration = animationTime

                if self.isFadeIn == false {

                    if animationTime > delayTime{

                        animationDuration = delayTime

                    }

                }

            default:

                delayTime = Double(arc4random_uniform(UInt32(durationTime/2.0 * 100)))/100.0

                let animationTime = durationTime - delayTime

                animationDuration = (Double(arc4random_uniform(UInt32(animationTime * 100)))/100.0)

            }

            delayTimeArray.append(delayTime)

            animationTimeArray.append(animationDuration)

            if self.displayType == .middle{

                delayTimeArray.reverse()

                animationTimeArray.reverse()

            }

        }

        if self.displayType == .descend{

            delayTimeArray.reverse()

            animationTimeArray.reverse()

        }

    }


最后,在屏幕每次刷新,selector方法调用时,计算每个文字的显示情况以及透明度,注意透明度是根据当前时间与动画开始时间,动画周期,文字的动画显示时长综合关联计算出来的,此处也是该效果的实现核心。

   func updateLabelDisplay(displayLink: CADisplayLink) -> Void {

        guard self.attributedTextString != nil else {

            return

        }

        guard self.endTime != nil else {

            return

        }

        let nowTime = CACurrentMediaTime()

        let attributedLength = self.attributedTextString?.length

        for index in 0..<attributedLength! {

            self.attributedTextString?.enumerateAttributes(in: NSMakeRange(index, 1), options: NSAttributedString.EnumerationOptions.longestEffectiveRangeNotRequired, using: {(value, range, error) -> Void in

                let colorA = value[NSAttributedStringKey.foregroundColor] as! UIColor

                let colorAlpha = colorA.cgColor.alpha

                let isNeedUpdate = (nowTime - self.beginTime!) > self.delayTimeArray[index] || (isFadeIn && colorAlpha < 1.0) || (!isFadeIn && colorAlpha > 0.0)

                if isNeedUpdate == false {

                    return

                }

                var percentage = (nowTime - self.beginTime! - self.delayTimeArray[index])/self.animationTimeArray[index]

                if !self.isFadeIn {

                    percentage = 1 - percentage

                }

//                let color = self.textColor.withAlphaComponent(CGFloat(percentage))

                let color = colorA.withAlphaComponent(CGFloat(percentage))

                self.attributedTextString?.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)

            })

        }

        super.attributedText = self.attributedTextString

        if nowTime > self.endTime! {

            self.mkDisplayLink?.isPaused = true

            guard self.completion != nil else {

                return

            }

            self.completion!(true, self.text!)

        }

    }

此处仅写出了三个比较核心的函数,来讲解具体实现的步骤,因为我的开源库实现的功能比较多,此处不便一一贴出代码详解,有兴趣的同学可以去我的Github上下载一下源码查看https://github.com/minhechen/MKLabel欢迎讨论。

最后,推广时间,求关注,求star,谢谢你的时间。

愿世界更美好。

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

推荐阅读更多精彩内容