快速上手IOS UIBezierPath(贝塞尔曲线)

2020-01-18 21:43:05王旭

UIBezierPath主要用来绘制矢量图形,它是基于Core Graphics对CGPathRef数据类型和path绘图属性的一个封装,所以是需要图形上下文的(CGContextRef),所以一般UIBezierPath在drawRect中使用。

使用方法

UIBezierPath 是对 CGPathRef 的封装。创建矢量图形时,拆解成一或多条线段,拼接起来,每条线段的终点都是下一条线段的起点。

具体地:

1.创建一个 UIBezierPath 对象

2.用 moveToPoint: 设置初始线段的起点

3.添加线段,定义一或多个子路径

4.修改 UIBezierPath 的绘图相关的属性,比如stroke path的属性 lineWidth 和 lineJoinStyle ,filled path的属性 usesEvenOddFillRule

注意:如果是矩形或者圆之类的特殊图形,可以不用第2步。

代码案例

画直线


UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(50, 50)];
[path addLineToPoint:CGPointMake(100, 50)];
path.lineWidth = 5.0f;
path.lineJoinStyle = kCGLineJoinRound;
[path stroke];

uibezierpath,ios,贝塞尔曲线,贝塞尔曲线案例

创建三角形


UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(50, 50)];
[path addLineToPoint:CGPointMake(300, 50)];
[path addLineToPoint:CGPointMake(200, 150)];
// 最后的闭合线是可以通过调用closePath方法来自动生成的,也可以调用-addLineToPoint:方法来添加
// [path addLineToPoint:CGPointMake(50, 50)];
[path closePath];
path.lineWidth = 5.0f;
[path stroke];

uibezierpath,ios,贝塞尔曲线,贝塞尔曲线案例

创建矩形


UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(50, 100, 50, 50)];
path.lineWidth = 5.0f;
[path stroke];

uibezierpath,ios,贝塞尔曲线,贝塞尔曲线案例

创建内切曲线


UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 200, 50, 50)];
path.lineWidth = 5.0f;
[path stroke];

uibezierpath,ios,贝塞尔曲线,贝塞尔曲线案例


 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 200, 50, 100)];
 path.lineWidth = 5.0f;
 [path stroke];