iOS 使用Shimmer来在Swift工程中添加微光闪烁的特效

释放双眼,带上耳机,听听看~!

Shimmer是Facebook在Paper中用于添加微光闪烁特效标签的工具,可实现类似iPhone滑动锁屏的效果如图:
效果如图

 

Swift工程中添加Shimmer

若要在Swift工程中使用Objective-C的类库,需添加Bridging Header文件

//  DemoShimmerBridgingHeader.h
#import "FBShimmering.h"
#import "FBShimmeringLayer.h"
#import "FBShimmeringView.h"

在Build Settings里边的Swift Complier中添加Objective-C的Bridging Header文件即可:
这里写图片描述

使用实例

Shimmer的使用非常简单,要先设置好FBShimmeringView或者FBShimmeringLayer,并设置shimmering属性为true,然后添加其contentView即可。

let shimmerView = FBShimmeringView(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
shimmerView.center = self.view.center
self.view.addSubview(shimmerView)
shimmerView.backgroundColor = UIColor.darkGrayColor()
shimmerView.shimmering = true
let label = UILabel(frame: CGRectMake(0, 200, self.view.frame.size.width, 50))
label.textAlignment = NSTextAlignment.Center
label.textColor = UIColor.whiteColor()
label.text = ">>>  Slide to unlock"
shimmerView.contentView = label
let swipeGesture = UISwipeGestureRecognizer(target: self, action: Selector("unlock:"))
swipeGesture.direction = UISwipeGestureRecognizerDirection.Right
shimmerView.addGestureRecognizer(swipeGesture)

注意:

  • 要将需要添加闪烁特效的控件(UILabel等)设置为shimmerView的contentView才行,而非仅仅添加为subview。

Shimmer的原理

Shimmer使用了CALayer的mask属性来触发闪烁特效,使用了CoreAnimation的time特性来确保动画效果的流程。

How exactly does Shimmer work?
There are three main components to Shimmer:
1. FBShimmering is a protocol that defines the list of properties that all shimmering views should have – both FBShimmeringView and FBShimmeringLayer implement this protocol.
2. FBShimmeringView is UIView subclass that acts as manager for the view you want to shimmer. Its contentView property has a setter method that adds your view as a subview and saves a reference to the subview’s CALayer to use when shimmering. Notice that each property is simply a pass-through to its underlying FBShimmerLayer.
3. FBShimmeringLayer is where all the magic happens. It creates a CAGradientLayer subclass and sets it as the mask of the contentView. Usually when you set a mask on a layer, you use it to “cut out” only part of a layer to be visible, but you can also use masks to make parts of a layer more or less transparent than others; this is what Shimmer does.

Basically Shimmer sets up the gradient layer to make part of the content view more transparent than other parts – i.e. the area that is “not shimmering” is 50% transparent, and the area that is shimmering is not transparent at all, so it appears like a highlight. It also runs an animation to move the gradient along the shimmer view, from left to right by default.

Demo

Demo地址: DemoShimmer

人已赞赏
iOS文章

iOS13适配踩坑记录

2020-3-26 14:55:33

iOS文章

iOS 侧滑返回过程中导航栏的黑色问题解决办法

2020-3-27 12:11:17

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索