Fork me on GitHub

Programming Design Notes

iPhone 轉換 UIView 時的動畫效果

| Comments

Apple 提供了流暢的動畫功能給各位開發者,差不多每一個 App 都會用到的動畫功能,無需複雜的程式碼便可以輕鬆使用到。
在這裡簡單介紹一下。

使用以下的程式碼便可以制作出動畫效果。
UIViewAnimationTransition transition = UIViewAnimationTransitionCurlUp;
UIViewAnimationCurve curve = UIViewAnimationCurveEaseInOut;
[UIView beginAnimations:@"anim" context:NULL];
[UIView setAnimationCurve:curve];
[UIView setAnimationTransition:transition forView:[self view] cache:YES];
[UIView setAnimationDuration:1.0f];
[UIView commitAnimations];

現在雖然有動畫效果,但頁面還是沒有改變,例如要新增一個黑色的頁面。
以下程式碼要加到動畫程式碼之前。
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[view setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:view];

完整轉頁效果:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[view setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:view];

UIViewAnimationTransition transition = UIViewAnimationTransitionCurlUp;
UIViewAnimationCurve curve = UIViewAnimationCurveEaseInOut;
[UIView beginAnimations:@"anim" context:NULL];
[UIView setAnimationCurve:curve];
[UIView setAnimationTransition:transition forView:[self view] cache:YES];
[UIView setAnimationDuration:1.0f];
[UIView commitAnimations];
[view release];

是否很簡單? 其實 Apple 已經提供了四動晝效果和四種速度變化。

向上翻頁的效果:
//Curl Up
UIViewAnimationTransition transition = UIViewAnimationTransitionCurlUp;

向下翻頁的效果:
//Curl Down
UIViewAnimationTransition transition = UIViewAnimationTransitionCurlDown;

由左向右旋轉的效果:
//Flip From Left
UIViewAnimationTransition transition = UIViewAnimationTransitionFlipFromLeft;

由右向左旋轉的效果:
//Flip From Right
UIViewAnimationTransition transition = UIViewAnimationTransitionFlipFromRight;

開始時慢慢加速,結束前慢慢減速:
UIViewAnimationCurve curve = UIViewAnimationCurveEaseInOut;

開始時慢慢加速:
UIViewAnimationCurve curve = UIViewAnimationCurveEaseIn;

結束前慢慢減速:
UIViewAnimationCurve curve = UIViewAnimationCurveEaseOut;

開始到尾也是均速:
UIViewAnimationCurve curve = UIViewAnimationCurveLinear;

大家可以試試那一個效果最適合你的 App。

相關書籍: More iPhone 3 Development: Tackling iPhone SDK 3 (Beginning)Beginning iPhone 3 Development: Exploring the iPhone SDKiPhone SDK 3 Programming: Advanced Mobile Development for Apple iPhone and iPod touch (Wiley)