? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 音量振動條的效果圖
相信大家對老版音樂播放界面的音量振動條都還有印象,那時候的音樂播放就是像上圖一樣的界面,小時候的我對此是深感神奇的,而今天我就來實現這個功能去找回童年的記憶。
? ? ? ? ?關鍵點分析: 多個圖層,設置動畫的縮放,延時操作。
? ? ? ? 具體實現:? ? 在這里如果創建多個視圖,然后一個個去設置它們的動畫延時時間無疑是非常浪費精力的,在這里我們就可以用到一個比較實用的東西了:復制圖層(CAReplicatorLayer),它可以對一個圖層進行復用,而我們這里的圖層的動畫動畫都是類似的,用它再合適不過了。而它的用法也很簡單,只要將要復用的圖層調用addSublayer這個方法加入就行了。
實現代碼:
@interface ViewController (){
UIView *backgroundView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//設置灰色背景
backgroundView = [[UIView alloc]initWithFrame:CGRectMake(20, 100, 360, 300)];
backgroundView.backgroundColor = [UIColor grayColor];
[self.view addSubview:backgroundView];
[self addLayer];
}
//設置圖層
- (void)addLayer{
//復制圖層,可以把圖層里面的所有子層復制,創建一個和背景視圖一樣大的復制圖層
CAReplicatorLayer *repl = [CAReplicatorLayer layer];
repl.frame = backgroundView.bounds;
[backgroundView.layer addSublayer:repl];
//用來復用的圖層位置和動畫的設置
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor whiteColor].CGColor;
layer.position = CGPointMake(15, 300);
layer.anchorPoint = CGPointMake(0.5, 1);
layer.bounds = CGRectMake(0, 0, 30, 270);
[repl addSublayer:layer];
//核心動畫實現伸縮
CABasicAnimation *animation = [CABasicAnimation animation];
animation.keyPath = @"transform.scale.y";
animation.toValue = @0.5;
animation.duration = 1;
animation.repeatCount = MAXFLOAT;
//設置動畫的反轉效果
animation.autoreverses = YES;
[layer addAnimation:animation forKey:nil];
//設置復制子層的數量,包括原始層
repl.instanceCount = 9;
//設置子層的偏移量,相對于原始層偏移
repl.instanceTransform = CATransform3DMakeTranslation(40, 0, 0);
//設置復制層動畫延遲時間
repl.instanceDelay = 0.2;
//設置子層的顏色,如果原始層不是白色,這里設置為綠色或其他的顏色會有問題
repl.instanceColor = [UIColor greenColor].CGColor;
//設置顏色的漸變量
repl.instanceGreenOffset = -0.1;
}