老谭笔记

OSX的动画实现(三)——自定义NSAnimation

在前面的文章有介绍到如何使用AppKit中提供的NSViewAnimation来实现,但通过看到类的继承关系可以发现,NSViewAnimation是继承于NSAnimation的,但却没有介绍如何使用NSAnimation,其实NSAnimation是和CAAnimation非常相似的,都是动画类的基类,它是对动画行为的抽象,却并不与实际的动画效果绘制有任何的关联。

以下代码我们创建了一个NSAnimation的子类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@protocol McSwitchAnimationDelegate
- (void)animation:(NSAnimation *)animation progressDidChanged:(float)progress;
@end
@interface McSwitchAnimation : NSAnimation
@property (nonatomic,unsafe_unretained) id delegate;
@end
@implementation McSwitchAnimation
@synthesize delegate;
- (id)delegate
{
return (id)[super delegate];
}
- (void)setDelegate:(id)aDelegate
{
[super setDelegate:aDelegate];
delegate = aDelegate;
}
- (void)setCurrentProgress:(NSAnimationProgress)progress
{
[super setCurrentProgress:progress];
[self.delegate animation:self progressDidChanged:progress];
}
@end

我们重写了Delegate,新增加了一个进度监测的回调,并重写了setCurrentProgress方法,并把当前的进度发送给代理,而代码来刷新界面。

示例代码下载:McAnimation_NSAnimation

该示例代码通过McSwitchAnimation实现了两个NSImageView的切换,并在代码中使用了CIFilter来增强切换效果,以下是实际运行效果:

animation_22