最近研究了一些頁面進出的動畫效果,主要使用 UIView 的 animateWithDuration 方法。當然,早期的 beginAnimations 也能達到同樣效果。以下記錄幾種常見做法。
先把 view 的 center 設到螢幕下方(畫面外),再動畫移動到目標位置:
-(void)fadeIn {
CGRect rect = [[UIScreen mainScreen] bounds];
self.view.center = CGPointMake(rect.size.width / 2, 720);
[UIView animateWithDuration:0.5f animations:^{
self.view.center = CGPointMake(rect.size.width / 2, 240 + 10);
} completion:^(BOOL finished) {
// 動畫完成後要做的事
}];
}
-(void)fadeOut {
CGRect rect = [[UIScreen mainScreen] bounds];
[UIView animateWithDuration:0.5f animations:^{
self.view.center = CGPointMake(rect.size.width / 2, 720);
} completion:^(BOOL finished) {
[imageView cancelImageLoad];
[imageView release];
}];
}
如果用舊的 beginAnimations,寫法如下:
CGRect rect = [[UIScreen mainScreen] bounds];
self.myimg.center = CGPointMake(rect.size.width / 2, 720);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
self.myimg.center = CGPointMake(rect.size.width / 2, 720);
[UIView commitAnimations];
掌握的核心觀念其實很簡單:只要設定 center 座標,動畫就會把 view 從目前位置平滑移動到新位置。
下列屬性都能放進動畫區塊中做出轉場效果:
[UIView animateWithDuration:1.0 animations:^{
firstView.alpha = 0.0;
secondView.alpha = 1.0;
}];
參數補充:completion 是動畫執行完畢後要執行的區塊;options 是動畫執行的選項(如節奏曲線);delay 是動畫開始前的等待時間。相較之下,animateWithDuration 的 block 寫法比舊的 beginAnimations/commitAnimations 更直覺、更易讀,是新專案的首選。