前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS_运用CAShapeLayer和UIBezierPath实现的环形进度条

iOS_运用CAShapeLayer和UIBezierPath实现的环形进度条

作者头像
mikimo
发布2022-07-20 14:03:07
4830
发布2022-07-20 14:03:07
举报
文章被收录于专栏:iOS开发~

主要代码如下:

代码语言:javascript
复制
#import "MOAnnularProgressView.h"

@implementation MOAnnularProgressView {
  CAShapeLayer *backgroundLayer;  // 背景图层
  CAShapeLayer *frontFillLayer;   // 填充图层
  UIBezierPath *backgroundPath;   // 背景贝赛尔曲线
  UIBezierPath *frontFillPath;    // 填充贝赛尔曲线
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self setupView];
  }
  return self;
}

- (instancetype)init {
  self = [super init];
  if (self) {
    [self setupView];
  }
  return self;
}

- (void)setupView {
  backgroundLayer = [CAShapeLayer layer];
  backgroundLayer.fillColor = nil;
  [self.layer addSublayer:backgroundLayer];

  frontFillLayer = [CAShapeLayer layer];
  frontFillLayer.fillColor = nil;
  frontFillLayer.lineCap = kCALineCapRound;//指定线的边缘是圆的
  [self.layer addSublayer:frontFillLayer];
}

- (void)layoutSubviews {
  [super layoutSubviews];
  CGFloat width = self.bounds.size.width;
  backgroundLayer.frame = self.bounds;
  backgroundPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(width/2.0f, width/2.0f) radius:width/2.0f startAngle:0 endAngle:M_PI*2 clockwise:YES];
  backgroundLayer.path = backgroundPath.CGPath;
  
  frontFillLayer.frame = self.bounds;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor {
  _backgroundColor = backgroundColor;
  backgroundLayer.strokeColor = _backgroundColor.CGColor;
}

- (void)setFrontColor:(UIColor *)frontColor {
  _frontColor = frontColor;
  frontFillLayer.strokeColor = _frontColor.CGColor;
}

- (void)setLineWidth:(CGFloat)lineWidth {
  _lineWidth = lineWidth;
  backgroundLayer.lineWidth = _lineWidth;
  frontFillLayer.lineWidth = _lineWidth;
}

- (void)setProgress:(CGFloat)progress {
  _progress = MAX(MIN(progress, 1.0), 0.0);
  CGFloat width = self.bounds.size.width;
  frontFillPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(width/2.0, width/2.0) 
                                                 radius:width/2.0f
                                             startAngle:-0.25*2*M_PI 
                                               endAngle:(2*M_PI)*_progress - 0.25*2*M_PI 
                                              clockwise:YES];
  frontFillLayer.path = frontFillPath.CGPath;
}


@end

Demo地址

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-11-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档