您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 中的常見動畫效果:旋轉、平移與切換

編輯:iOS 相關資訊

動畫是提升 iOS 應用體驗的重要手段。本文整理幾種常見動畫的實作方式,包括圖片自動旋轉、頁面切換以及平移效果。

圖片自動旋轉

CABasicAnimation 是一種最多隻有兩個關鍵幀的動畫,適合表現從起始到結束的簡單變化。以下讓 UIImageView 持續旋轉:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"7"]];
imageView.frame = CGRectMake(40, 60, 200, 250);
[self.view addSubview:imageView];

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
animation.delegate = self;
animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI, 0, 0, 1.0)];
animation.duration = 30;        // 執行時間
animation.cumulative = YES;     // 累積旋轉
animation.repeatCount = INT_MAX; // 執行次數
animation.autoreverses = YES;   // 是否自動重複
[imageView.layer addAnimation:animation forKey:@"animation"];

使用 CATransition 實現頁面切換

透過 CATransition 可以實現類似 UINavigationController 的 push 與 pop 效果。CATransition 使用了 type(過渡種類:淡化、推擠、揭開、覆蓋)與 subtype(過渡方向:上下左右)兩個概念。此外还有一些私有的動畫類型,如立方體(cube)、吸收、翻轉、波紋、翻頁、鏡頭開關等。

CATransition *myT = [CATransition animation];
myT.timingFunction = UIViewAnimationCurveEaseInOut;
myT.type = @"cube";              // 動畫類型
myT.subtype = kCATransitionFromLeft; // 動畫方向
myT.duration = 0.5;
[self.navigationController.view.layer addAnimation:myT forKey:nil];

建立 UIView 動畫(過渡效果)

方法一:使用動畫塊(block)語法,在 animations 區塊中描述目標狀態,並在 completion 區塊中處理完成後的回復:

[UIView animateWithDuration:0.5 animations:^{
    CGRect frames = self.view_1.frame;
    frames.origin.x = 160;
    self.view_1.frame = frames;
    // 縮放
    self.view_1.transform = CGAffineTransformScale(self.view_1.transform, 0.01, 0.01);
} completion:^(BOOL finished) {
    CGRect frames = self.view_1.frame;
    frames.origin.x = 0;
    self.view_1.frame = frames;
    self.view_1.transform = CGAffineTransformIdentity; // 恢復原始縮放
}];

方法二:使用 begin/commit 動畫方式,並透過代理在動畫結束後執行回呼,使視圖回到原來位置:

-(void)button22
{
    [UIView beginAnimations:@"testAnimation" context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationStop)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    CGRect frames = self.view_1.frame;
    frames.origin.x = 160;
    self.view_1.frame = frames;
    [UIView commitAnimations];
}

-(void)animationStop
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    CGRect frames = self.view_1.frame;
    frames.origin.x = 0;
    self.view_1.frame = frames;
    [UIView commitAnimations];
}

掌握這些基礎動畫 API,就能為應用加入流暢自然的動態效果,大幅提升使用者體驗。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved