使用CADisplayLink实现UILabel动画特效

在开发时,咱们有时候会遇到须要定时对UIView进行重绘的需求,进而让view产生不一样的动画效果。html

本文项目ios

效果图

typewritter

shine

fade

wave

初探 CADisplayLink

定时对View进行定时重绘可能会第一时间想到使用NSTimer,可是这样的动画实现起来是不流畅的,由于在timer所处的runloop中要处理多种不一样的输入,致使timer的最小周期是在50到100毫秒之间,一秒钟以内最多只能跑20次左右。git

但若是咱们但愿在屏幕上看到流畅的动画,咱们就要维持60帧的刷新频率,也就意味着每一帧的间隔要在0.016秒左右,NSTimer是没法实现的。因此要用到Core Animation的另外一个timer,CADisplayLinkgithub

CADisplayLink的头文件中,咱们能够看到它的使用方法跟NSTimer是十分相似的,其一样也是须要注册到RunLoop中,但不一样于NSTimer的是,它在屏幕须要进行重绘时就会让RunLoop调用CADisplayLink指定的selector,用于准备下一帧显示的数据。而NSTimer是须要在上一次RunLoop整个完成以后才会调用制定的selector,因此在调用频率与上比NSTimer要频繁得多。swift

另外和NSTimer不一样的是,NSTimer能够指定timeInterval,对应的是selector调用的间隔,但若是NSTimer触发的时间到了,而RunLoop处于阻塞状态,其触发时间就会推迟到下一个RunLoop。而CADisplayLink的timer间隔是不能调整的,固定就是一秒钟发生60次,不过能够经过设置其frameInterval属性,设置调用一次selector之间的间隔帧数。另外须要注意的是若是selector执行的代码超过了frameInterval的持续时间,那么CADisplayLink就会直接忽略这一帧,在下一次的更新时候再接着运行。数组

配置 RunLoop

在建立CADisplayLink的时候,咱们须要指定一个RunLoop和RunLoopMode,一般RunLoop咱们都是选择使用主线程的RunLoop,由于全部UI更新的操做都必须放到主线程来完成,而在模式的选择就能够用NSDefaultRunLoopMode,可是不能保证动画平滑的运行,因此就能够用NSRunLoopCommonModes来替代。可是要当心,由于若是动画在一个高帧率状况下运行,会致使一些别的相似于定时器的任务或者相似于滑动的其余iOS动画会暂停,直到动画结束。app

private func setup() {
	_displayLink = CADisplayLink(target: self, selector: #selector(update))
	_displayLink?.isPaused = true
	_displayLink?.add(to: RunLoop.main, forMode: .commonModes)
}

复制代码

实现不一样的字符变换动画

在成功创建CADisplayLink计时器后,就能够着手对字符串进行各种动画操做了。在这里咱们会使用NSAttributedString来实现效果dom

setupAnimatedText(from labelText: String?)这个方法中,咱们须要使用到两个数组,一个是durationArray,一个是delayArray,经过配置这两个数组中的数值,咱们能够实现对字符串中各个字符的出现时间出现时长的控制。函数

打字机效果的配置

  • 每一个字符出现所需时间相同
  • 下一个字符等待上一个字符出现完成后再出现
  • 经过修改NSAttributedStringKey.baselineOffset调整字符位置
case .typewriter:
	attributedString.addAttribute(.baselineOffset, value: -label.font.lineHeight, range: NSRange(location: 0, length: attributedString.length))
	let displayInterval = duration / TimeInterval(attributedString.length)
	for index in 0..<attributedString.length {
		durationArray.append(displayInterval)
		delayArray.append(TimeInterval(index) * displayInterval)
	}

复制代码

闪烁效果的配置

  • 每一个字符出现所需时间随机
  • 确保全部字符可以在duration内均完成出现
  • 修改NSAttributedStringKey.foregroundColor透明度来实现字符的出现效果
case .shine:
	attributedString.addAttribute(.foregroundColor, value: label.textColor.withAlphaComponent(0), range: NSRange(location: 0, length: attributedString.length))
	for index in 0..<attributedString.length {
		delayArray.append(TimeInterval(arc4random_uniform(UInt32(duration) / 2 * 100) / 100))
		let remain = duration - Double(delayArray[index])
		durationArray.append(TimeInterval(arc4random_uniform(UInt32(remain) * 100) / 100))
	}
复制代码

渐现效果的配置

  • 每一个字符出现所需时间渐减
  • 修改NSAttributedStringKey.foregroundColor透明度来实现字符的出现效果
case .fade:
	attributedString.addAttribute(.foregroundColor, value: label.textColor.withAlphaComponent(0), range: NSRange(location: 0, length: attributedString.length))
	let displayInterval = duration / TimeInterval(attributedString.length)
	for index in 0..<attributedString.length  {
		delayArray.append(TimeInterval(index) * displayInterval)
		durationArray.append(duration - delayArray[index])
	}
复制代码

完善每一帧的字符串更新效果

接下来就须要完善刚才在CADisplayLink中配置的update方法了,在这个方法中咱们会根据咱们刚才配置的两个数组中的相关数据对字符串进行变换。oop

核心代码

  • 经过开始时间当前时间获取动画进度
  • 根据字符位置对应duationArraydelayArray中的数据
  • 根据durationArraydelayArray中的数据计算当前字符的显示进度
var percent = (CGFloat(currentTime - beginTime) - CGFloat(delayArray[index])) / CGFloat(durationArray[index])
percent = fmax(0.0, percent)
percent = fmin(1.0, percent)
attributedString.addAttribute(.baselineOffset, value: (percent - 1) * label!.font.lineHeight, range: range)
复制代码

随后即可以将处理完的NSAttributedString返回给label进行更新

番外:利用正弦函数实现波纹进度

波纹路径

首先介绍一下正弦函数:y = A * sin(ax + b)

  • 在 x 轴方向平移 b 个单位(左加右减)
  • 横坐标伸长(0 < a < 1)或者缩短(a > 1) 1/a 倍
  • 纵坐标伸长(A > 1)或者缩短(0 < A < 1)A 倍

在简单了解了这些知识后,咱们回到wavePath()方法中,在这个方法咱们使用正弦函数来绘制一段UIBezierPath

let originY = (label.bounds.size.height + label.font.lineHeight) / 2
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: _waveHeight!))
var yPosition = 0.0
for xPosition in 0..<Int(label.bounds.size.width) {
	yPosition = _zoom! * sin(Double(xPosition) / 180.0 * Double.pi - 4 * _translate! / Double.pi) * 5 + _waveHeight!
	path.addLine(to: CGPoint(x: Double(xPosition), y: yPosition))
}
path.addLine(to: CGPoint(x: label.bounds.size.width, y: originY))
path.addLine(to: CGPoint(x: 0, y: originY))
path.addLine(to: CGPoint(x: 0, y: _waveHeight!))
path.close()
复制代码

波纹高度与动画的更新

  • 随着进度高度不断升高
  • 随着进度波纹不断波动

CADisplayLink注册的update的方法中,咱们对承载了波纹路径的Layer进行更新

_waveHeight! -= duration / Double(label!.font.lineHeight)
_translate! += 0.1
if !_reverse {
	_zoom! += 0.02
	if _zoom! >= 1.2 {
		_reverse = true
	}
} else {
	_zoom! -= 0.02
	if _zoom! <= 1.0 {
		_reverse = false
	}
}
shapeLayer.path = wavePath()
复制代码

结语

以上就是我对CADisplayLink的一些运用,其实它的使用方法还有不少,能够利用它实现更多更复杂而精美的动画,同时但愿各位若是有更好的改进也能与我分享。

若是你喜欢这个项目,欢迎到GitHub上给我一个star。

参考

相关文章
相关标签/搜索