UIBezierPath主要用来绘制矢量图形,它是基于Core Graphics对CGPathRef数据类型和path绘图属性的一个封装,所以是需要图形上下文的(CGContextRef),所以一般UIBezierPath在drawRect中使用。
直接画个圆吧!
创建一个CustonView继承自UIView
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface CustonView : UIView
/// 进度(值范围0.0~1.0,默认0.0)
@property (nonatomic, assign) CGFloat progress;
@end
NS_ASSUME_NONNULL_END
在.m文件重写
- (void)drawRect:(CGRect)rect {
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width/2.f,self.bounds.size.height/2.f)radius:self.bounds.size.width/2.f startAngle:0 endAngle:M_PI *2*self.progress clockwise:YES];
//创建一个shapeLayer
CAShapeLayer *layer = [CAShapeLayer layer];
layer.frame = self.bounds;
layer.path = path.CGPath; //从bezier曲线获取到的形状
layer.strokeColor = [UIColor greenColor].CGColor; //边缘线的颜色
layer.fillColor = [UIColor clearColor].CGColor; //闭环填充的颜色
layer.lineCap = kCALineCapSquare; //边缘线的类型
layer.lineWidth = 4.0f; //线条宽度
// layer.strokeStart = 0.0f;
// layer.strokeEnd = 0.0f;
// self.layer.mask = layer;
// [path stroke];
// //将layer添加进图层
[self.layer addSublayer:layer];
}
- (void)setProgress:(CGFloat)progress {
_progress = progress;
[self setNeedsDisplay];
}
使用
#import "CustonView.h"
@interface xxxxxxVC ()
@property (nonatomic , strong)NSTimer *timer;
@property (nonatomic , assign)float index;
@property (nonatomic , strong)CustonView *showView;
@end
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self LayerTest];
self.view.backgroundColor = [UIColor whiteColor];
self.index = 0.01;
self.timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(timerEvent) userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerEvent {
self.index+=0.01;
NSLog(@"%f",self.index);
if (self.index >=1) {
[self.timer invalidate];
self.timer = nil;
}
self.showView.progress = self.index;
}
#pragma mark --- CALayer
- (void)LayerTest {
self.showView = [[CustonView alloc] initWithFrame:CGRectMake(100,200, 100, 100)];
self.showView.backgroundColor = [UIColor whiteColor];
self.showView.alpha =0.5;
[self.view addSubview:self.showView];
}