標籤:視圖動畫
NSViewAnimation和NSAnimation提供了視圖的簡單動畫效果。NSViewAnimation是從NSAnimation繼承下來的。這個類提供了一個簡便的方式去給多個視圖或視窗做動畫效果。動畫的效果可以改變視圖的位置,大小,淡入淡出。
- (id)initWithViewAnimations:(NSArray*)viewAnimations
初始化方法需要參數是一個包含字典對象的數組對象。這個字典對象資訊包含4個鍵值對。如下
NSString *NSViewAnimationTargetKey;NSString *NSViewAnimationStartFrameKey;NSString *NSViewAnimationEndFrameKey;NSString *NSViewAnimationEffectKey;
第一個key值所對應的對象是必須的,可以是一個NSView或NSWindow的對象。也就是指定哪一個視圖或者視窗去做動畫效果。
第二個key值所對應的對象就是視圖或者視窗的動畫起始frame。frame包括視圖或視窗位置和大小。
第三個key值所對應的對象就是視圖的或視窗的結束frame。
第四個key值對象的對象就是動畫的效果,是淡入效果,還是淡出效果。這個屬性是可選的。
完成初始化之後,設定NSViewAnimation對象的一些屬性,比如動畫的期間等。設定動畫期間:
- (void)setDuration:(NSTimeInterval)duration
啟動動畫方法:
- (void)startAnimation
以下是一個demo
#import "AppDelegate.h"@implementation AppDelegate- (void)dealloc{ [super dealloc];}- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{ // Insert code here to initialize your application}//以下動畫實現:firstView上移50.secondView實現消失效果- (IBAction)startAnimations:(id)sender{ // firstView, secondView are outlets NSViewAnimation *theAnim; NSRect firstViewFrame; NSRect newViewFrame; NSMutableDictionary* firstViewDict; NSMutableDictionary* secondViewDict; { firstViewDict = [NSMutableDictionary dictionaryWithCapacity:3]; firstViewFrame = [firstView frame]; [firstViewDict setObject:firstView forKey:NSViewAnimationTargetKey]; //設定視圖的起始位置 [firstViewDict setObject:[NSValue valueWithRect:firstViewFrame] forKey:NSViewAnimationStartFrameKey]; // 改變視圖1的位置,並把改變之後的位置變為視圖結束位置 newViewFrame = firstViewFrame; newViewFrame.origin.x += 0; //x不變, newViewFrame.origin.y += 50; //y加50 [firstViewDict setObject:[NSValue valueWithRect:newViewFrame] forKey:NSViewAnimationEndFrameKey]; } { secondViewDict = [NSMutableDictionary dictionaryWithCapacity:3]; //設定目標視圖 [secondViewDict setObject:secondView forKey:NSViewAnimationTargetKey]; //設定視圖的結束位置。 NSRect viewZeroSize = [secondView frame]; viewZeroSize.size.width = 0; viewZeroSize.size.height = 0; [secondViewDict setObject:[NSValue valueWithRect:viewZeroSize] forKey:NSViewAnimationEndFrameKey]; // 設定視圖淡出效果 [secondViewDict setObject:NSViewAnimationFadeOutEffect forKey:NSViewAnimationEffectKey]; } theAnim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObjects:firstViewDict, secondViewDict, nil]]; // 設定動畫的一些屬性.比如期間0.5秒 [theAnim setDuration:0.5]; // a half seconds. [theAnim setAnimationCurve:NSAnimationEaseIn]; // 啟動動畫 [theAnim startAnimation]; [theAnim release];}
運行開始前:
點擊Button運行之後:
NSViewAnimation視圖的簡單動畫