CAReplicatorLayer的目的是为了高效生成许多相似的图层。它会绘制一个或多个图层的子图层,并在每个复制体上应用不同的变换。它自己能够重建包括自己在内的n个copies,这些copies是原layer中的所有sublayers,并且任何对原layer的sublayers设置的transform是可以积累的(accumulative).
下面直接上代码操作:
/**
反射效果: 使用CAReplicatorLayer创建了一个实时的『反射』效果.
*/
func testFunctionTwo(){
let replicatorLayer: CAReplicatorLayer = CAReplicatorLayer()
replicatorLayer.frame = CGRect(x: 100, y: 50, width: 100, height: 100)
replicatorLayer.contents = UIImage(named: "ptjShare")?.CGImage
replicatorLayer.instanceCount = 2 //注意:是包括自己在内总共为2
view.layer.addSublayer(replicatorLayer)
var transform: CATransform3D = CATransform3DIdentity
let verticalOffset: CGFloat = replicatorLayer.bounds.height;
transform = CATransform3DTranslate(transform, 0, verticalOffset , 0)
transform = CATransform3DRotate(transform, CGFloat(M_PI), 0, 0,1 )
replicatorLayer.instanceTransform = transform
replicatorLayer.instanceAlphaOffset = -0.6
replicatorLayer.instanceBlueOffset = -0.1
replicatorLayer.instanceGreenOffset = -0.1
replicatorLayer.instanceRedOffset = -0.1
let layer:CALayer = CALayer()
layer.frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
layer.contents = UIImage(named: "ptjShare")?.CGImage
layer.backgroundColor = UIColor.whiteColor().CGColor
replicatorLayer.addSublayer(layer)
}
/**
函数一 实现一个圆圈效果
*/
func testFunctionOne(){
//create a replicator layer and add it to our view
let replicatorLayer: CAReplicatorLayer = CAReplicatorLayer()
replicatorLayer.frame = CGRect(x: 100, y: 50, width: 100, height: 100)
view.layer.addSublayer(replicatorLayer)
//设置复制对象的个数(图层需要重复多少次),默认一个,可动画属性.
replicatorLayer.instanceCount = 10
//对每一个复制子 layer 的位置进行调整.
var transform: CATransform3D = CATransform3DIdentity
transform = CATransform3DTranslate(transform, 0, 200, 0)
transform = CATransform3DRotate(transform, CGFloat(M_PI / 5.0), 0, 0, 1)
transform = CATransform3DTranslate(transform,0, -200, 0)
//instanceTransform指定了一个CATransform3D3D变换(这种情况下,下一图层的位移和旋转将会移动到圆圈的下一个点,变换是逐步增加的,每个实例都是相对于前一实例布局.
replicatorLayer.instanceTransform = transform
//注意到当图层在重复的时候,他们的颜色也在变化:这是用instanceBlueOffset和instanceGreenOffset属性实现的。通过逐步减少蓝色和绿色通道,我们逐渐将图层颜色转换成了红色.
replicatorLayer.instanceBlueOffset = -0.1
replicatorLayer.instanceGreenOffset = -0.1
//添加子layer.实现相应的效果.
let layer:CALayer = CALayer()
layer.frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
layer.backgroundColor = UIColor.whiteColor().CGColor
replicatorLayer.addSublayer(layer)
}
效果图:
http://www.ios-animations-by-emails.com/posts/2015-march#tutorial
https://github.com/gontovnik/DGActivityIndicatorView
IOS使用CAReplicatorLayer重建动态的倒影:
http://tuohuang.info/14.html#.Vm-axRp971w