iOS動畫(Core Animation)

Core Animation(核心動畫)簡介

  • 它是一組非常強(qiáng)大的動畫處理API,使用它能做出非常炫麗的動畫效果。
  • Core Animation的動畫執(zhí)行過程都是在后臺操作的,不會阻塞主線程兼砖。
  • Core Animation是直接作用在CALayer上的,并非UIView既棺。
CAAnimation是所有動畫類的父類讽挟,但是它不能直接使用,應(yīng)該使用它的子類丸冕。
  • CAPropertyAnimation是CAAnimation的子類耽梅,但是不能直接使用,要想創(chuàng)建動畫對象胖烛,應(yīng)該使用它的兩個子類:CABasicAnimation和CAKeyframeAnimation
  • 能用的動畫類只有4個子類:CABasicAnimation眼姐、CAKeyframeAnimation、CATransition佩番、CAAnimationGroup

平移動畫

示例代碼

@interface ViewController () 

@property (nonatomic, weak) CALayer *layer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    CALayer *layer = [CALayer layer];
    layer.bounds = CGRectMake(0, 0, 50, 50);
    layer.position = CGPointMake(50, 50);
    // 設(shè)置layer的錨點(diǎn)為左上角(0众旗,0)
    layer.anchorPoint = CGPointMake(0, 0);
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.cornerRadius = 10;
    
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 創(chuàng)建核心動畫
    CABasicAnimation *anim = [CABasicAnimation animation];
    
    // 要執(zhí)行什么樣的動畫
    anim.keyPath = @"position";
    
    // 通過動畫,將layer從哪兒移動到哪兒
    anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
    anim.toValue  = [NSValue valueWithCGPoint:CGPointMake(200, 300)];
    
    // 完成動畫所需要消耗的時間
    anim.duration  = 2;
    
    // 動畫執(zhí)行完畢之后不刪除動畫
    anim.removedOnCompletion = NO;
    // 保存動畫的最新狀態(tài)
    anim.fillMode = kCAFillModeForwards;
    
    // 設(shè)置動畫的代理趟畏,可以監(jiān)聽動畫的執(zhí)行過程贡歧,這里設(shè)置控制器為代理
    anim.delegate = self;
    
    //添加核心動畫到layer
    [self.layer addAnimation:anim forKey:nil];
}

- (void)animationDidStart:(CAAnimation *)anim {
    NSLog(@"執(zhí)行前: %@", NSStringFromCGPoint(self.layer.position));
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    NSLog(@"執(zhí)行后: %@", NSStringFromCGPoint(self.layer.position));
}
驗(yàn)證圖層的屬性值還是動畫執(zhí)行前的初始值{50,50}赋秀,并沒有真正被改變
  • 實(shí)質(zhì)上利朵,圖層的屬性值還是動畫執(zhí)行前的初始值,并沒有真正被改變
position.png

縮放動畫

代碼示例:

@interface ViewController () 

@property (nonatomic, weak) CALayer *layer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    CALayer *layer = [CALayer layer];
    layer.bounds = CGRectMake(0, 0, 50, 50);
    layer.position = CGPointMake(50, 50);
    // 設(shè)置layer的錨點(diǎn)為左上角(0沃琅,0)
    layer.anchorPoint = CGPointMake(0, 0);
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.cornerRadius = 10;
    
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 創(chuàng)建核心動畫
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"bounds"];
    
    // 設(shè)置動畫執(zhí)行時間
    anim.duration  = 2;
    
    // 動畫執(zhí)行完畢之后不刪除動畫
    anim.removedOnCompletion = NO;
    // 保存動畫的最新狀態(tài)
    anim.fillMode = kCAFillModeForwards;
    
    // 修改屬性哗咆,執(zhí)行動畫
    anim.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 200, 200)];
    //添加核心動畫到layer
    [self.layer addAnimation:anim forKey:nil];
}

旋轉(zhuǎn)動畫

示例代碼:

@interface ViewController () 

@property (nonatomic, weak) CALayer *layer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    CALayer *layer = [CALayer layer];
    layer.bounds = CGRectMake(0, 0, 150, 50);
    layer.position = CGPointMake(50, 50);
    // 設(shè)置layer的錨點(diǎn)為左上角(0蜘欲,0)
    layer.anchorPoint = CGPointMake(0, 0);
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.cornerRadius = 10;
    
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
     // 創(chuàng)建動畫
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform"];
    // 設(shè)置動畫執(zhí)行時間
    anim.duration  = 2;
  // 修改屬性益眉,執(zhí)行動畫
    anim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_4, 1, 1, 0)];
    // 動畫執(zhí)行完畢之后不刪除動畫
    anim.removedOnCompletion = NO;
    // 保存動畫的最新狀態(tài)
    anim.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:anim forKey:nil]; 
}

關(guān)鍵幀動畫簡介

是CApropertyAnimation的子類,跟CABasicAnimation的區(qū)別是:CABasicAnimation只能從一個數(shù)值(fromValue)變到另一個數(shù)值(toValue),而CAKeyframeAnimation會使用一個NSArray保存這些數(shù)值
示例代碼:

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *customerView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 創(chuàng)建動畫
    CAKeyframeAnimation *keyAnim = [CAKeyframeAnimation animation];
    // 要執(zhí)行什么樣的動畫
    keyAnim.keyPath = @"position";
    NSValue *value1=[NSValue valueWithCGPoint:CGPointMake(100, 100)];
    NSValue *value2=[NSValue valueWithCGPoint:CGPointMake(200, 100)];
    NSValue *value3=[NSValue valueWithCGPoint:CGPointMake(200, 200)];
    NSValue *value4=[NSValue valueWithCGPoint:CGPointMake(100, 200)];
    NSValue *value5=[NSValue valueWithCGPoint:CGPointMake(100, 100)];
    keyAnim.values=@[value1,value2,value3,value4,value5];
    
    // 動畫執(zhí)行完畢之后不刪除動畫
    keyAnim.removedOnCompletion = NO;
    // 保存動畫的最新狀態(tài)
    keyAnim.fillMode = kCAFillModeForwards;
     // 設(shè)置動畫執(zhí)行時間
    keyAnim.duration = 3.0;
    // 設(shè)置代理
    keyAnim.delegate = self;
    // 設(shè)置動畫的節(jié)奏
    keyAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //添加核心動畫到layer
    [self.customerView.layer addAnimation:keyAnim forKey:nil];
}

- (void)animationDidStart:(CAAnimation *)anim {
    NSLog(@"開始動畫");
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    NSLog(@"結(jié)束動畫");
}

停止動畫(可以通過path屬性郭脂,讓layer在指定的軌跡上運(yùn)動)

代碼示例如下

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *customerView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 創(chuàng)建動畫
    CAKeyframeAnimation *keyAnim = [CAKeyframeAnimation animation];
    // 平移
    keyAnim.keyPath = @"position";
    // 創(chuàng)建一條路徑
    CGMutablePathRef path = CGPathCreateMutable();
    // 設(shè)置一個圓的路徑
    CGPathAddEllipseInRect(path, NULL, CGRectMake(150, 100, 100, 100));
    keyAnim.path = path;
    
    //有create就一定要有release
    CGPathRelease(path);
    
    // 動畫執(zhí)行完畢之后不刪除動畫
    keyAnim.removedOnCompletion = NO;
    // 保存動畫的最新狀態(tài)
    keyAnim.fillMode = kCAFillModeForwards;
    // 設(shè)置動畫執(zhí)行時間
    keyAnim.duration = 3.0;
    
    // 設(shè)置動畫的節(jié)奏
    keyAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //添加核心動畫到layer
    [self.customerView.layer addAnimation:keyAnim forKey:@"next"];

}

- (IBAction)stop {
    // 停止self.customView.layer上名稱標(biāo)示為nextone的動畫
    [self.customerView.layer removeAnimationForKey:@"next"];
}

圖標(biāo)抖動

#define angle2Radian(angle) ((angle)/180.0*M_PI)

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 創(chuàng)建動畫
    CAKeyframeAnimation *keyAnim = [CAKeyframeAnimation animation];
    // 要執(zhí)行什么樣的動畫
    keyAnim.keyPath = @"transform.rotation";
    // 設(shè)置動畫時間
    keyAnim.duration = 0.1;
    // 設(shè)置圖片抖動弧度
    // 把度數(shù)轉(zhuǎn)換為弧度(度數(shù)/180*M_PI)
    keyAnim.values = @[@(-angle2Radian(6)), @(angle2Radian(6)), @(-angle2Radian(6))];
    // 設(shè)置動畫的重復(fù)次數(shù)
    keyAnim.repeatCount = MAXFLOAT;
    // 動畫執(zhí)行完畢之后不刪除動畫
    keyAnim.removedOnCompletion = NO;
    // 保存動畫的最新狀態(tài)
    keyAnim.fillMode = kCAFillModeForwards;
    [self.iconImageView.layer addAnimation:keyAnim forKey:nil];

}

轉(zhuǎn)場動畫和組動畫

  • CATransition(轉(zhuǎn)場動畫)是CAAnimation的子類年碘,能夠?yàn)閷犹峁┮瞥銎聊缓鸵迫肫聊坏膭赢嬓Ч?/li>
  • UINavigationController就是通過CATransition實(shí)現(xiàn)了將控制器的視圖推入屏幕的動畫效果

屬性解析:
type:動畫過渡類型
subtype:動畫過渡方向
startProgress:動畫起點(diǎn)(在整體動畫的百分比)
endProgress:動畫終點(diǎn)(在整體動畫的百分比)

代碼示例

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, assign) NSInteger index;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.index = 1;
}


- (IBAction)preClick:(id)sender {
    self.index--;
    if (self.index < 1) {
        self.index = 3;
    }
    self.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"Guide%ld", self.index]];
    // 創(chuàng)建核心動畫
    CATransition *anim = [CATransition animation];
    //設(shè)置過度效果
    anim.type = @"cube";
    //設(shè)置動畫的過度方向(向左
    anim.subtype = kCATransitionFromLeft;
    anim.duration = 2.0;
    [self.imageView.layer addAnimation:anim forKey:nil];
}

- (IBAction)nextClick:(id)sender {
    self.index++;
    if (self.index > 3) {
        self.index = 1;
    }
    self.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"Guide%ld", self.index]];
    // 創(chuàng)建核心動畫
    CATransition *anim = [CATransition animation];
    //設(shè)置過度效果
    anim.type = @"cube";
    //設(shè)置動畫的過度方向(向左
    anim.subtype = kCATransitionFromRight;
    anim.duration = 2.0;
    // 設(shè)置動畫的起點(diǎn)
    anim.startProgress = 0.5;
    [self.imageView.layer addAnimation:anim forKey:nil];
}

動畫組(平移-旋轉(zhuǎn)-縮放作為一組動畫一起執(zhí)行)

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *iconView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 平移動畫
    CABasicAnimation *a1 = [CABasicAnimation animation];
    a1.keyPath = @"transform.translation.y";
    a1.toValue = @(300);
    
    // 縮放動畫
    CABasicAnimation *a2 = [CABasicAnimation animation];
    a2.keyPath = @"transform.scale";
    a2.toValue = @(0.0);
    
    // 旋轉(zhuǎn)動畫
    CABasicAnimation *a3 = [CABasicAnimation animation];
    a3.keyPath = @"transform.rotation";
    a3.toValue = @(M_PI_2);
    
    // 組動畫
    CAAnimationGroup *groupAnim = [CAAnimationGroup animation];
    groupAnim.animations  = @[a1, a2, a3];
    
    groupAnim.duration = 3;
    groupAnim.fillMode = kCAFillModeForwards;
    groupAnim.removedOnCompletion = NO;
    
    [self.iconView.layer addAnimation:groupAnim forKey:nil];
}

UIView封裝動畫

  • UIKit直接將動畫集成到UIView類中,當(dāng)內(nèi)部的一些屬性發(fā)生改變時展鸡,UIView將為這些改變提供動畫支持

代碼示例

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *customerView;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 首尾式動畫
   [UIView beginAnimations:nil context:nil];
    //執(zhí)行動畫
    //設(shè)置動畫執(zhí)行時間
    [UIView setAnimationDuration:2.0];
    self.customerView.center=CGPointMake(200, 300);
    //設(shè)置代理
    [UIView setAnimationDelegate:self];
    //設(shè)置動畫執(zhí)行完畢調(diào)用的事件
    [UIView setAnimationDidStopSelector:@selector(didStopAnimation)];
}

- (void)didStopAnimation {
    NSLog(@"動畫執(zhí)行完畢");
}

注:UIView封裝的動畫執(zhí)行完畢之后不會反彈屿衅。即如果是通過CALayer核心動畫改變layer的位置狀態(tài),表面上看雖然已經(jīng)改變了莹弊,但是實(shí)際上它的位置是沒有改變的

block動畫

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *customerView;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    /*
     duration:動畫的持續(xù)時間
     delay:動畫延遲delay秒后開始
     options:動畫的節(jié)奏控制
     animations:將改變視圖屬性的代碼放在這個block中
     completion:動畫結(jié)束后涤久,會自動調(diào)用這個block
     */
    [UIView animateWithDuration:2.0
                          delay:3.0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         self.customerView.center=CGPointMake(200, 300);
                     }
                     completion:^(BOOL finished) {
                         NSLog(@"動畫執(zhí)行完畢");
                     }];
    
    
}

轉(zhuǎn)場動畫

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *customerView;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [UIView transitionWithView:self.customerView
                      duration:3.0
                       options:0
                    animations:^{
                        self.customerView.center=CGPointMake(200, 300);
                    } completion:^(BOOL finished) {
                        NSLog(@"動畫執(zhí)行完畢");
                    }];
}

UIImageView的幀動畫

UIImageView可以讓一系列的圖片在特定的時間內(nèi)按順序顯示

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *images;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (NSMutableArray *)images {
    if (!_images) {
        _images = [NSMutableArray array];
        for (int i = 0; i < 4; i++) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", i]];
            [_images addObject:image];
        }
    }
    return _images;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _imageView.userInteractionEnabled = YES;
    _imageView.animationImages = self.images;
    _imageView.animationDuration = 1.0;
    _imageView.animationRepeatCount = 0;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (![_imageView isAnimating]) {
        [_imageView startAnimating];
    } else {
        [_imageView stopAnimating];
    }
}

相關(guān)鏈接:
Core Animation核心動畫

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末忍弛,一起剝皮案震驚了整個濱河市响迂,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌细疚,老刑警劉巖蔗彤,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異疯兼,居然都是意外死亡然遏,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進(jìn)店門吧彪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來待侵,“玉大人,你說我怎么就攤上這事来氧〗敫” “怎么了?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵啦扬,是天一觀的道長中狂。 經(jīng)常有香客問我,道長扑毡,這世上最難降的妖魔是什么胃榕? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮瞄摊,結(jié)果婚禮上勋又,老公的妹妹穿的比我還像新娘。我一直安慰自己换帜,他們只是感情好楔壤,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著惯驼,像睡著了一般蹲嚣。 火紅的嫁衣襯著肌膚如雪递瑰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天隙畜,我揣著相機(jī)與錄音抖部,去河邊找鬼。 笑死议惰,一個胖子當(dāng)著我的面吹牛慎颗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播言询,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼俯萎,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了运杭?” 一聲冷哼從身側(cè)響起讯屈,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎县习,沒想到半個月后涮母,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡躁愿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年叛本,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片彤钟。...
    茶點(diǎn)故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡来候,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出逸雹,到底是詐尸還是另有隱情营搅,我是刑警寧澤,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布梆砸,位于F島的核電站转质,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏帖世。R本人自食惡果不足惜休蟹,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望日矫。 院中可真熱鬧赂弓,春花似錦、人聲如沸哪轿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽窃诉。三九已至杨耙,卻和暖如春姓惑,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背按脚。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留敦冬,地道東北人辅搬。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像脖旱,于是被迫代替她去往敵國和親堪遂。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,974評論 2 355

推薦閱讀更多精彩內(nèi)容