您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

為 iOS App 加入啟動畫面的漸變淡出效果

編輯:iOS 開發綜合

由於系統預設的啟動畫面(Launch Image)在 App 就緒後是瞬間消失、直接硬切到主畫面,視覺上顯得突兀。在 Apple 提供原生的轉場 API 之前,只能自己在 App 啟動後補上一段過渡動畫。


做法是在 application:didFinishLaunchingWithOptions: 的最後,把啟動圖當成一張 UIImageView 蓋在視窗上,然後用 UIView 的動畫 API 讓它放大並淡出:


- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController"
                                                          bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    UIImageView *splashScreen = [[[UIImageView alloc] initWithFrame:self.window.bounds]
                                  autorelease];
    splashScreen.image = [UIImage imageNamed:@"Default"];
    [self.window addSubview:splashScreen];

    [UIView animateWithDuration:1.0 animations:^{
        CATransform3D transform = CATransform3DMakeScale(1.5, 1.5, 1.0);
        splashScreen.layer.transform = transform;
        splashScreen.alpha = 0.0;
    } completion:^(BOOL finished) {
        [splashScreen removeFromSuperview];
    }];

    return YES;
}

這段程式碼的關鍵在於動畫的兩個屬性同時變化:


  • alpha 從 1 降到 0:產生淡出效果,讓啟動畫面漸漸消失
  • transform 放大到 1.5 倍:產生一個輕微向前推進的錯覺,比單純淡出更有層次感

1.0 秒的 duration 是個耐看的長度;太短會感覺還是硬切,太長則會讓使用者覺得 App 很慢。


另外,completion 區塊裡的 removeFromSuperview 不能省。動畫結束後那個 imageView 已經完全透明,若不移除,它仍然留在視窗上繼續攔截觸控事件——畫面看似正常,但使用者會發現怎麼點都沒反應。


這裡還有個細節:程式中使用的 imageNamed:@"Default" 對應的就是你的啟動圖檔名。如果啟動圖在不同裝置上有多個尺寸版本,記得依實際情況挑選,或改用 +[UIImage imageNamed:] 的自動匹配機制,避免在較大螢幕上出現鋸齒。


補充一個現代寫法上的差異:在 ARC 環境下不需要 autorelease,而 UIView animateWithDuration: 這類 block 語法從 iOS 4 起就已可用,是目前最簡潔的動畫寫法,比起舊式的 beginAnimations / commitAnimations 好讀得多。

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