创建基本动画
这效果是从MOV文件转成GIF的,而且CSDN不支持大于2M的图片上传,优酷地址
创建一个Single View Application工程,再创建一个Swift文件,我创建的叫“PulsingRadarView”,目前结构为:
在ViewController里面持有一个Optional的PulsingRadarView的属性,表示可以为nil,然后在viewDidLoad里做一个简单的初始化工作:
classViewController:UIViewController{
varradarView:PulsingRadarView!
overridefuncviewDidLoad() {
super.viewDidLoad()
letradarSize =CGSizeMake(self.view.bounds.size.width,)
radarView=PulsingRadarView(frame:CGRectMake(0,(self.view.bounds.size.height-radarSize.height)/2,
radarSize.width,radarSize.height))
view.addSubview(radarView)
}
funcdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
雷达是圆形的,所以宽高都是self.view.bounds.size.width。
PulsingRadarView里面现在应该是空的,我们首先导入QuartzCore,因为后面动画部分会用到CALayer,然后重写drawRect方法:
funcdrawRect(rect:CGRect) {
UIColor.whiteColor().setFill()
UIRectFill(rect)
letpulsingCount =6
letanimationDuration:Double=4
varanimationLayer =CALayer()
forvari =0; i < pulsingCount; i++ {
varpulsingLayer =CALayer()
pulsingLayer.frame=height)
pulsingLayer.borderColor=UIColor.grayColor().CGColor
pulsingLayer.borderWidth=1
pulsingLayer.cornerRadius= rect.2
defaultCurve =CAMediaTimingFunction(name:kCAMediaTimingFunctionDefault)
varanimationGroup =CAAnimationGroup()
animationGroup.fillMode=kCAFillModeBackwards
animationGroup.beginTime=CACurrentMediaTime() +Double(i) * animationDuration /Double(pulsingCount)
animationGroup.duration= animationDuration
animationGroup.repeatCount=HUGE
animationGroup.timingFunction= defaultCurve
varscaleAnimation =CABasicAnimation(keyPath:"transform.scale")
scaleAnimation.autoreverses=false
scaleAnimation.fromValue=Double(0)
scaleAnimation.toValue=1.5)
varopacityAnimation =CAKeyframeAnimation(keyPath:"opacity")
opacityAnimation.values= [1),0.7),216)">0)]
opacityAnimation.keyTimes= [0),216)">0.5),216)">1)]
animationGroup.animations= [scaleAnimation,opacityAnimation]
pulsingLayer.addAnimation(animationGroup,forKey:"pulsing")
animationLayer.addSublayer(pulsingLayer)
}
layer.addSublayer(animationLayer)
}