Mac上的进度条动画

在iOS上写一个进度动画很容易,在Mac平台上相同风格的进度条思路也是差不多的,今天就最近项目中开发的一组动画中的一个,来分析一下Mac下写动画效果的注意点。




ok,现在选一例自己感觉还是有一定难度动画6、圆形图片上传进行说明:
首先,要思考要实现像第6个动画的形式的实现细节,并对动画进行分解。这个动画类似水箱注水的过程,在水逐渐注入水箱的过程中,水位逐渐上升,逐渐贮满;
1
2
3
-(BOOL) isFlipped{
return YES;
}

由于Mac OS中view的坐标系在左下,iOS中view的坐标系在左上,有了之前在iOS上开发相同类型的动画经验,首先先反转坐标系保持和iOS上的一致,这样后面的代码就可以继承iOS上的了

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
- (void)drawRect:(CGRect)rect{
CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
CGFloat radius = MIN(rect.size.width * 0.5, rect.size.height * 0.5)-2;
CGFloat xCenter = rect.size.width * 0.5;
CGFloat yCenter = rect.size.height * 0.5;
[[NSColor clearColor] setFill];
[[NSColor whiteColor] setStroke];
CGFloat w = radius * 2;
CGFloat h = w;
CGFloat x = (rect.size.width - w) * 0.5;
CGFloat y = (rect.size.height - h) * 0.5;
CGContextAddEllipseInRect(ctx, CGRectMake(x, y, w, h));
CGContextDrawPath(ctx,kCGPathFillStroke);
[[NSColor grayColor] set];
CGFloat startAngle = M_PI * 0.5 - self.progress * M_PI;
CGFloat endAngle = M_PI * 0.5 + self.progress * M_PI;
CGContextAddArc(ctx, xCenter, yCenter, radius, startAngle, endAngle, 0);
CGContextFillPath(ctx);
NSString *progressStr = [NSString stringWithFormat:@"%.0f%%", self.progress * 100];
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSFontAttributeName] = [NSFont boldSystemFontOfSize:14];
attributes[NSForegroundColorAttributeName] = [NSColor whiteColor];
[self setCenterProgressText:progressStr withAttributes:attributes];
}

核心代码

1
2
CGFloat startAngle = M_PI * 0.5 - self.progress * M_PI;
CGFloat endAngle = M_PI * 0.5 + self.progress * M_PI;

水位逐渐上升,则类似不停一个以y轴对称的圆弧,弧度不停的增加,直至变成圆
因此先计算出圆弧的起始角度,同时计算出以Y轴对称的结束角度,接着在两个角度间形成的圆弧填充颜色就可以了。
代码已经分享到github了,欢迎star
Demo in Github