最近碰到一个需求,需要画一个仪表盘的页面。图上所示。
计算角度
圆弧部分还好,用CAShapeLayer+UIBezierPath曲线,只要确定好圆心部分和左右两边的角度就行。这里正好说明一下
- (void)addArcWithCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise API_AVAILABLE(ios(4.0));
这个接口startAngle、endAngle和clockwise的关系,之前一直记不太清。
我们需要看一下下面这张图
clockwise为true的时候,就会从startAngle按顺时针方向画弧。为false的时候,按逆时针方向画弧。
这里有一个要注意的地方是
- 顺时针的360°表示的值,必须是0~2*M_PI,
- 逆时针的360°表示的值必须是0~-2*M_PI。
- 同一个角度表示的值,在clockwise取true或者false的情况下,是需要转换的。
了解了上面的注意点之后,三条圆弧还是能很方便的画出来的。
接下来就是动态的显示进度。即白色圆弧每次数值变化,弧线动态增长或减少。
StrokeEnd
一开始想的是每次都重新绘制贝塞尔曲线,但是发现从动画效果上来看,每次重新绘制,都会从起点位置绘制到终点位置。不是想要的效果。
然后又想着设置layer.masksToBounds=true然后,画一条半圆,通过旋转来达到左右移动的效果,这样超出layer的部分就不会显示了,但是又发现背景的圆弧不是一块半圆,会存在覆盖不全的情况。
后来查看CAShaperLayer的说明,发现这样一个属性
/* These values define the subregion of the path used to draw the
* stroked outline. The values must be in the range [0,1] with zero
* representing the start of the path and one the end. Values in
* between zero and one are interpolated linearly along the path
* length. strokeStart defaults to zero and strokeEnd to one. Both are
* animatable. */
@property CGFloat strokeStart;
@property CGFloat strokeEnd;
这两个值默认是0和1,对应的就是起始点和终点的比例,当storkeEnd=0.5
的时候,原来圆弧终点的值就会减少为原来的一半
那么我就可以这样了,我先画一套完整的覆盖背景圆弧的实线圆弧,设置strokeEnd=0
,这样圆弧长度就为0了。当值变化的时候,在调整strokeEnd的值。就可以动态的变化圆弧长度了。
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"
];
animation.duration = 1;
animation.fromValue = @(oldValue/100.0);
animation.toValue = @(value/100.0);
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[self.valueLayer addAnimation:animation forKey:@"valueProgress"
];
绘制移动路径
搞定了圆弧的变化之后,还有一部分是小圆点的移动,它是按照圆弧的轨迹移动的,那么在做动画效果的时候,就要让小圆点按照圆弧的轨迹移动位置。
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
CGFloat outerWidth = 226;
if (oldValue > value) { // <-
CGFloat valueAngle = value/100.0 * (2*M_PI - (self.startAngle - self.endAngle)) + self.startAngle;
CGFloat oldAngle = oldValue/100.0 * (2*M_PI - (self.startAngle - self.endAngle)) + self.startAngle;
valueAngle = valueAngle - 2*M_PI;
oldAngle = oldAngle - 2*M_PI;
[be