通过使用NSViewAnimation实现View的变化

简介

NSViewAnimation提供了NSView或NSWindow简易的动画效果,可以改变NSView或NSWindow的位置、大小并实现NSView或NSWindow的渐入、渐出效果。

接口说明

1、初始化

1
- (id)initWithViewAnimations:(NSArray*)viewAnimations

NSViewAnimation的初始化需要一个包含字典对象的一个数组对象,其字典包含了4个键值对,如下表:

键值 需要传入的类型 意义
NSViewAnimationTargetKey 视图或窗口对象 实现动画效果的视图或窗口
NSViewAnimationStartFrameKey NSRect对象 动画起始frame(位置与大小)
NSViewAnimationEndFrameKey NSRect对象 动画结束frame(位置与大小)
NSViewAnimationEffectKey NSString对象 淡入或淡出效果(可选)

2、设置动画的持续时间

1
- (void)setDuration:(NSTimeInterval)duration

(不要被NSTimeInterval类型所吓到,实际上NSTimeInterval等同于double类型。)

3、播放动画

1
- (void)startAnimation

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//实现NSView或NSWindow的移动
-(void)startAnimation:(id)animationTarget endPoint:(NSPoint)endPoint{
NSRect startFrame = [animationTarget frame];
NSRect endFrame = NSMakeRect(endPoint.x, endPoint.y, startFrame.size.width, startFrame.size.height);

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:

animationTarget,NSViewAnimationTargetKey,

NSViewAnimationFadeInEffect,NSViewAnimationEffectKey,

[NSValue valueWithRect:startFrame],NSViewAnimationStartFrameKey,

[NSValue valueWithRect:endFrame],NSViewAnimationEndFrameKey, nil];

NSViewAnimation *animation = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dictionary]];
animation.delegate = self;
animation.duration = 2;
//NSAnimationBlocking阻塞
//NSAnimationNonblocking异步不阻塞
//NSAnimationNonblockingThreaded线程不阻塞
[animation setAnimationBlockingMode:NSAnimationNonblocking];
[animation startAnimation];
}

代码

https://github.com/gaoxiaodiao/mac_sample/tree/master/animationSample_1