UIBezierPath主要用來繪制矢量圖形艇潭,它是基于Core Graphics對CGPathRef數(shù)據(jù)類型和path繪圖屬性的一個封裝末捣,所以是需要圖形上下文的(CGContextRef)允华,所以一般UIBezierPath在drawRect中使用。
直接畫個圓吧!
創(chuàng)建一個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];
//創(chuàng)建一個shapeLayer
CAShapeLayer *layer = [CAShapeLayer layer];
layer.frame = self.bounds;
layer.path = path.CGPath; //從bezier曲線獲取到的形狀
layer.strokeColor = [UIColor greenColor].CGColor; //邊緣線的顏色
layer.fillColor = [UIColor clearColor].CGColor; //閉環(huán)填充的顏色
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];
}