需求:近期项目中有横向柱状图的需求,很容易想到基于CAShapeLayer去实现,在实现柱状图展示动画的过程中有了一些踩坑经历,这里贴出来源代码供大家参考。
showCode:
- (void)drawRectangleLayerWithRect:(CGRect)rect cornerRadius:(CGFloat)cornerRadius fillColor:(UIColor)fillColor inView:(UIView)view animate:(BOOL)animate duration:(CGFloat)duration {
//图形类型的图层
CAShapeLayer *sLayer = [CAShapeLayer layer];
sLayer.backgroundColor = fillColor.CGColor;
sLayer.frame = rect;
//下面的两行代码是动画需要的属性设置,因为可能会有子视图动画需求
sLayer.position = rect.origin;
sLayer.anchorPoint = CGPointZero;
//添加边框
sLayer.borderColor = fillColor.CGColor;
sLayer.borderWidth = 1;
sLayer.cornerRadius = cornerRadius;
[view.layer addSublayer:sLayer];
if (animate) {
CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"];
boundsAnimation.fromValue = [NSValue valueWithCGRect: CGRectMake(rect.origin.x, rect.origin.y, 0, rect.size.height)] ;
boundsAnimation.toValue = [NSValue valueWithCGRect:rect];
boundsAnimation.duration = duration; // 持续时间
boundsAnimation.removedOnCompletion = NO;
boundsAnimation.fillMode = kCAFillModeForwards;
// 动画缓慢的进入,中间加速,然后减速的到达目的地。
boundsAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[sLayer addAnimation:boundsAnimation forKey:@""];
}
}
网友评论