iPhone開發創建連續動畫案例
iPhone開發創建連續動畫案例是本文要介紹的內容,主要詳細介紹了在iphone開發中連續動畫的實現。來看詳細內容。在iphone開發中,我們有些時候需要創建連續的動畫效果,使用戶體驗更好。
連續動畫就是一段動畫運行完畢后調用另一段動畫,一定要保證兩段動畫沒有重疊,本文不打算使用CAKeyframeAnimation建立連續的動畫塊,雖然使用CAKeyframeAnimation更簡單(在其他的博文中實現此方法)
大概有兩種方法可以選擇:
1.增加延遲以便在***段動畫結束之后在啟動第二段動畫([performSelector:withObject:afterDelay:])
2.指定動畫委托回調(animationDidStop:finished:context:)
從編程的角度來說就更容易,下面我們將擴展類UIView的方法,通過類別引入一個新的方法----commitModalAnimations.調用此方法而不是調用commitAnimations方法,它會建立一個新的runloop,該循環只有在動畫結束的時候才會停止。
這樣確保了commitModalAnimations方法只有在動畫結束才將控制權返還給調用方法,利用此擴展方法可以將動畫塊按順序放進代碼中,不必做任何其他的修改就能避免動畫的重疊現象。
代碼如下:
- @interface UIView (ModalAnimationHelper)
- + (void) commitModalAnimations;
- @end
- @interface UIViewDelegate : NSObject
- {
- CFRunLoopRef currentLoop;
- }
- @end
- @implementation UIViewDelegate
- -(id) initWithRunLoop: (CFRunLoopRef)runLoop
- {
- if (self = [super init]) currentLoop = runLoop;
- return self;
- }
- (void) animationFinished: (id) sender
- {
- CFRunLoopStop(currentLoop);
- }
- @end
- @implementation UIView (ModalAnimationHelper)
- + (void) commitModalAnimations
- {
- CFRunLoopRef currentLoop = CFRunLoopGetCurrent();
- UIViewDelegate *uivdelegate = [[UIViewDelegate alloc] initWithRunLoop:currentLoop];
- [UIView setAnimationDelegate:uivdelegate];
- [UIView setAnimationDidStopSelector:@selector(animationFinished:)];
- [UIView commitAnimations];
- CFRunLoopRun();
- [uivdelegate release];
- }
- @end
使用:
- [self.view viewWithTag:101].alpha = 1.0f;
- // Bounce to 115% of the normal size
- [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
- [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
- [UIView setAnimationDuration:0.4f];
- [self.view viewWithTag:101].transform = CGAffineTransformMakeScale(1.15f, 1.15f);
- [UIView commitModalAnimations];
- // Return back to 100%
- [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
- [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
- [UIView setAnimationDuration:0.3f];
- [self.view viewWithTag:101].transform = CGAffineTransformMakeScale(1.0f, 1.0f);
- [UIView commitModalAnimations];
- // Pause for a second and appreciate the presentation
- [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0f]];
- // Slowly zoom back down and hide the view
- [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
- [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
- [UIView setAnimationDuration:1.0f];
- [self.view viewWithTag:101].transform = CGAffineTransformMakeScale(0.01f, 0.01f);
- [UIView commitModalAnimations];
小結:iPhone開發創建連續動畫案例的內容介紹完了,希望本文對你有所幫助!