这种方式是直接对图形上下文进行操作,常用的方法有:
之前的讲解文章:https://www.jianshu.com/p/f2841b6b9260
CGContextBeginPath //开始画路径
CGContextMoveToPoint //移动到某一点
CGContexAddLineToPoint //画直线
CGContexAddCurveToPoint //画饼图
CGContexAddEllipseInRect //画椭圆
CGContexAddArc //画圆
CGContexAddRect //画方框
CGContexClosePath //封闭当前路径
使用方法一绘制路径后将清空图形上下文,如果我们想保存路径来复用,可以使用Quartz提供的CGPath函数集合来创建可复用的路径对象。
CGPathCreateMutable
CGPathMoveToPoint
CGPathAddLineToPoint
CGPathAddCurveToPoint
CGPathAddEllipseInRect
CGPathAddArc
CGPathAddRect
CGPathCloseSubpath
这些函数和上面方法一的一一对应,可代替之使用。
UIBezierPath存在于UIKit中,是对路径绘制的封装,和CGContextRef类似,优点是更面向对象,我们可以像操作普通对象一样对其进行操作。
在自定义View的时候,一般使用UIBezierPath来创建路径就能基本满足我们的需求,推荐使用。
之前的讲解文章:https://www.jianshu.com/p/fc5a1e0372fa
- (void)drawRect:(CGRect)rect // 重写drawRect方法
{
// 1.初始化图形相应的UIBezierPath对象
UIBezierPath* aPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 200, 200)]; // 2.
// 2.设置一些修饰属性
aPath.lineWidth = 8.0;
//路径的终点形状,
aPath.lineCapStyle = kCGLineCapRound;
//路径的连接点形状
aPath.lineJoinStyle = kCGLineCapRound;
UIColor *color = [UIColor colorWithRed:0 green:0 blue:0.7 alpha:1];
[color set];
// 3.起点
[aPath moveToPoint:CGPointMake(20, 20)];
// 4.绘制线条
[aPath addLineToPoint:CGPointMake(100, 100)];
[aPath stroke]; // 渲染,完成绘制
}
//获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//绘制路径: 圆形(中心坐标200、200、半径100、起点弧度0、终点弧度2PI、画的方向0逆1正)
CGContextAddArc(ctx, 200, 200, 100, 0, M_PI * 2, 0);
//修改图形状态参数
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.9, 1.0);//笔颜色
CGContextSetLineWidth(ctx, 10);//线条宽度
//渲染上下文
CGContextStrokePath(ctx);
//获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//创建可变路径
CGMutablePathRef path = CGPathCreateMutable();
//添加圆形到路径中(所在路径、不进行变换操作、中心坐标200、200、起点弧度0、终点弧度2PI、画的方向0逆1正)
CGPathAddArc(path, NULL, 200, 200, 100, 0, M_PI * 2, 1);
//将路径添加到上下文
CGContextAddPath(ctx, path);
//修改图形状态参数
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.9, 1.0);//笔颜色
CGContextSetLineWidth(ctx, 10);//线条宽度
//渲染上下文
CGContextStrokePath(ctx);
//创建路径
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 100, 200, 200)];
//修改图形状态参数
[[UIColor colorWithRed:0.5 green:0.5 blue:0.9 alpha:1.0] setStroke];//笔颜色
[path setLineWidth:10];//线条宽度
//渲染
[path stroke];
- (void)drawRect:(CGRect)rect {
}
- (void)drawRect:(CGRect)rect {
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 100, 200, 200)];
[[UIColor colorWithRed:0.5 green:0.5 blue:0.9 alpha:1.0] setStroke];
[path setLineWidth:10];
[path stroke];
}
- (void)viewDidLoad {
[super viewDidLoad];
CircleView * cricleView = [[CircleView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:cricleView];
}
效果图