UIBezeirPath是Core Graphics
框架关于路径的封装,使用这个类可以定义简单的形状, such as 圆 椭圆 直线 曲线等
UIBezierPath
是CGPathRef
数据类型的封装。如果是基于矢量形状的路径,都用直线和曲线去创建。我们使用直线段去创建矩形和多边形,使用曲线去创建圆弧(arc)、圆或者其他复杂的曲线形状。
- 创建一个
UIBezierPath
对象 - 调用
-moveToPoint:
设置初始线段的起点 - 添加线或者曲线去定义一个或者多个子路径
- 改变
UIBezierPath
对象跟绘图相关的属性。如,我们可以设置画笔的属性、填充样式等
UIBezierPath创建方法介绍
// 画三角形- (void)drawTrianglePath {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(20, 20)];
[path addLineToPoint:CGPointMake(self.frame.size.width - 40, 20)];
[path addLineToPoint:CGPointMake(self.frame.size.width / 2, self.frame.size.height - 20)];
// 最后的闭合线是可以通过调用closePath方法来自动生成的,也可以调用-addLineToPoint:方法来添加
// [path addLineToPoint:CGPointMake(20, 20)];
[path closePath];
// 设置线宽
path.lineWidth = 1.5;
// 设置填充颜色
UIColor *fillColor = [UIColor greenColor];
[fillColor set];
[path fill];
// 设置画笔颜色
UIColor *strokeColor = [UIColor blueColor];
[strokeColor set];
// 根据我们设置的各个点连线
[path stroke];
}
// 画矩形
- (void)drawRectPath {
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(20, 20, self.frame.size.width - 40, self.frame.size.height - 40)];
path.lineWidth = 1.5;
path.lineCapStyle = kCGLineCapRound;
path.lineJoinStyle = kCGLineJoinBevel;
// 设置填充颜色
UIColor *fillColor = [UIColor greenColor];
[fillColor set];
[path fill];
// 设置画笔颜色
UIColor *strokeColor = [UIColor blueColor];
[strokeColor set];
// 根据我们设置的各个点连线
[path stroke];
}
//画圆
- (void)drawCiclePath {
// 传的是正方形,因此就可以绘制出圆了
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 20, self.frame.size.width - 40, self.frame.size.width -40)];
// 设置填充颜色
UIColor *fillColor = [UIColor greenColor];
[fillColor set];
[path fill];
// 设置画笔颜色
UIColor *strokeColor = [UIColor blueColor];
[strokeColor set];
// 根据我们设置的各个点连线
[path stroke];
}
// 画椭圆
- (void)drawOvalPath {
// 传的是不是正方形,因此就可以绘制出椭圆圆了
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 20, self.frame.size.width - 80, self.frame.size.height -40)];
// 设置填充颜色
UIColor *fillColor = [UIColor greenColor];
[fillColor set];
[path fill];
// 设置画笔颜色
UIColor *strokeColor = [UIColor blueColor];
[strokeColor set];
// 根据我们设置的各个点连线
[path stroke];
}
//画带圆角的矩形
+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect
cornerRadius:(CGFloat)cornerRadius;
+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect
byRoundingCorners:(UIRectCorner)corners
cornerRadii:(CGSize)cornerRadii;
第一个工厂方法是画矩形,但是这个矩形是可以画圆角的。第一个参数是矩形,第二个参数是圆角大小。 第二个工厂方法功能是一样的,但是可以指定某一个角画成圆角。像这种我们就可以很容易地给UIView扩展添加圆角的方法了。
四个都是圆角10: