iOS中的動畫有兩種實現方式,一種是UIView來實現動畫,另外一種動畫是經過CALayer來實現,下面介紹兩種動畫的簡單實現:數組
1、UIView動畫的實現併發
UIView使用Context來實現動畫動畫
關鍵代碼:spa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//參數1 動畫名稱 參數2 要實現動畫的對象上下文
[UIView beginAnimations:@
"attribute"
context:_showImageView];
//設置動畫的時間
[UIView setAnimationDuration:1.0f];
//設置動畫延遲時間
// [UIView setAnimationDelay:2];
//設置視圖center 實現試圖移動動畫
_showImageView.center = CGPointMake(100, 100);
//設置alpha值:視圖透明度
_showImageView.alpha = 0.2f;
//設置背景顏色
_showImageView.backgroundColor = [UIColor greenColor];
//UIView動畫 設置代理
[UIView setAnimationDelegate:self];
//動畫將要開始代理方法
[UIView setAnimationWillStartSelector:@selector(animationWillStart:context:)];
//動畫已經結束代理方法
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
//提交動畫設置,執行動畫
[UIView commitAnimations];
|
使用Block實現的動畫:代理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
//UIView動畫, 使用Block實現
[UIView animateWithDuration:1.0f animations:^{
//經過設置translation 實現視圖的偏移
if
([self.mySwitch isOn]) {
//基於上一次的translation
_showImageView.transform = CGAffineTransformTranslate(_showImageView.transform, 50, 0);
}
else
{
//基於原始的translation
_showImageView.transform = CGAffineTransformMakeTranslation(-50, 0);
}
}];
|
2、CALayer動畫的實現code
CABasic動畫的實現:根據初始位置和結束位置肯定動畫orm
1
2
3
4
5
6
|
//CABasic 有兩個屬性 fromValue 動畫開始值,toValue動畫結束值
CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@
"position"
];
[animation1 setDuration:2];
animation1.fromValue = [NSValue valueWithCGPoint:CGPointMake(150, 150)];
animation1.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 200)];
[_imageView.layer addAnimation:animation1 forKey:@
"position"
];
|
建立一組動畫:對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//建立組動畫對象
CAAnimationGroup *group = [CAAnimationGroup animation];
//CABasic動畫
CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@
"transform.scale.y"
];
animation1.fromValue = @1.5;
animation1.toValue = @0.5;
//關鍵幀動畫
CAKeyframeAnimation *animation2 = [CAKeyframeAnimation animationWithKeyPath:@
"position"
];
animation2.values = @[[NSValue valueWithCGPoint:CGPointMake(100, 100)],
[NSValue valueWithCGPoint:CGPointMake(200, 150)],
[NSValue valueWithCGPoint:CGPointMake(100, 200)],
[NSValue valueWithCGPoint:CGPointMake(200, 250)]];
//group添加動畫數組,group中動畫對象併發執行
[group setAnimations:@[animation1, animation2]];
[group setDuration:4.0f];
[_imageView.layer addAnimation:group forKey:@
"group"
];
|