iOS开发基础篇--CAShapeLayer的strokeStart和strokeEnd属性

一、案例演示

最近有一个小需求,就是要做一个圆形进度条,大概样子如下:


1.gif。

在不知道有CAShapeLayer的strokeStart和strokeEnd属性的时候,我采取的方法就是实时的 移除旧的CAShapeLayer 然后重绘这个圆形的CAShapeLayer。显然这种方式的效率是不高的。后来在一次看别人Demo的时候,发现别人使用了CAShapeLayer的strokeStart和strokeEnd属性,实现这一个效果十分的简单方便。下面就和大家来讲一讲这两个属性的使用。

二、属性详解

苹果官方给出这两个属性的解释为:

  • 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. */

大概意思就是:我们可以对绘制的Path进行分区。这两个属性的值在0~1之间,0代表Path的开始位置,1代表Path的结束位置。是一种线性递增关系。strokeStart默认值为0,strokeEnd默认值为1。这两个属性都支持动画。

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = _demoView.bounds;
    shapeLayer.strokeEnd = 0.7f;
    shapeLayer.strokeStart = 0.1f;

    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:_demoView.bounds];

    shapeLayer.path = path.CGPath;

    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.lineWidth = 2.0f;
    shapeLayer.strokeColor = [UIColor redColor].CGColor;

    [_demoView.layer addSublayer:shapeLayer];
复制代码

我们通过以上代码设置:strokeStart=0.1f; strokeEnd=0.7f则显示如下图所示。

三、圆形进度条实现代码

综上所述我们知道,strokeStart和strokeEnd可以设置一条Path的起始和终止的位置,通过利用strokeStart和strokeEnd这两个属性支持动画的特点,我们通过以下代码就可以实现圆形进度条的效果。

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = _demoView.bounds;

    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:_demoView.bounds];

    shapeLayer.path = path.CGPath;

    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.lineWidth = 2.0f;
    shapeLayer.strokeColor = [UIColor redColor].CGColor;

    [_demoView.layer addSublayer:shapeLayer];

    CABasicAnimation *pathAnima = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnima.duration = 3.0f;
    pathAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnima.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnima.toValue = [NSNumber numberWithFloat:1.0f];
    pathAnima.fillMode = kCAFillModeForwards;
    pathAnima.removedOnCompletion = NO;
    [shapeLayer addAnimation:pathAnima forKey:@"strokeEndAnimation"];
复制代码

四、最后说一点

这是一个我的iOS交流群:624212887,群文件自行下载,不管你是小白还是大牛热烈欢迎进群 ,分享面试经验,讨论技术, 大家一起交流学习成长!希望帮助开发者少走弯路。——点击:加入

如果觉得对你还有些用,就关注小编+喜欢这一篇文章。你的支持是我继续的动力。

下篇文章预告:UITableview嵌套UITableView案例实践(仿淘宝商品详情页实现)

文章来源于网络,如有侵权,请联系小编删除。


转载于:https://juejin.im/post/5bfccdf3e51d456658738cf9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值