使用NSAnimationContext实现简单的NSView动画

来源:互联网 发布:php 高德地图api接口 编辑:程序博客网 时间:2024/06/06 04:33

文章转载自老谭笔记:http://www.tanhao.me/pieces/1504.html/


之前那系列关于动画的文章中一篇分享了如何为CALayer自定义动画,虽然代码也很简单,但毕竟还是要去实现两三个方法,其实用NSView去实现一个自定义的动画就显得更简单了,几乎可以算是只需要去实现一个方法,以下就是完整的代码:

此处忽略了头文件,头文件只是定义了一个属性progress而已

123456789101112131415161718192021222324252627282930313233343536373839404142
#import "THAnimationView.h"#import <QuartzCore/QuartzCore.h>@implementation THAnimationView@synthesize progress;- (double)progress{    return progress;}//此处必需去刷新界面,否则动画无效- (void)setProgress:(double)value{    progress = value;    [self setNeedsDisplay:YES];}//画一道弧线,用来展示动画- (void)drawRect:(NSRect)dirtyRect{    NSBezierPath *path = [NSBezierPath bezierPath];    NSPoint center = NSMakePoint(NSMidX(self.bounds), NSMidY(self.bounds));    [path appendBezierPathWithArcWithCenter:center radius:50 startAngle:0 endAngle:360*progress clockwise:NO];    [path setLineWidth:10];    [[NSColor redColor] set];    [path stroke];}//这就是你需要去实现的一个方法,根据属性返回一个动画对象+ (id)defaultAnimationForKey:(NSString *)key{    if ([key isEqualToString:@"progress"])    {        return [CABasicAnimation animation];    }else    {        return [super defaultAnimationForKey:key];    }}@end

当你需要展示动画时,只需要这样使用即可:

1
[[animationView animator] setProgress:1.0];

如果需要设置指定的动画时间,你还可以这样使用:

1234
[NSAnimationContext beginGrouping];[[NSAnimationContext currentContext] setDuration:1.0];[[animationView animator] setProgress:1.0];[NSAnimationContext endGrouping];

0 0