iOS UIBezierPath类 介绍
使用UIBezierPath类可以创建基于矢量的路径,这个类在UIKit中。此类是Core Graphics框架关于path的一个封装。使用此类可以定义简单的形状,如椭圆或者矩形,或者有多个直线和曲线段组成的形状。
Bezier Path 基础
- 使用UIBezierPath创建多边形
UIColor *color = [UIColor yellowColor];
[color set]; //设置线条颜色
UIBezierPath *aPath = [UIBezierPath bezierPath];
aPath.lineWidth = 2.0; //设置线宽
aPath.lineCapStyle = kCGLineCapRound; //线条拐角
aPath.lineJoinStyle = kCGLineCapRound; //终点处理
[aPath moveToPoint:CGPointMake(100, 20)];
[aPath addLineToPoint:CGPointMake(150, 50)];
[aPath addLineToPoint:CGPointMake(50, 50)];
[aPath closePath];
[aPath stroke];//根据坐标点连线 ([aPath fill];填充)
- 使用UIBezierPath创建矩形
UIColor color = [UIColor yellowColor];
[color set];
UIBezierPath aPath = [UIBezierPath bezierPathWithRect:CGRectMake(20, 20,100, 50)];
aPath.lineWidth = 2.0;
aPath.lineCapStyle = kCGLineCapRound;
aPath.lineJoinStyle = kCGLineCapRound;
[aPath stroke];
- 使用UIBezierPath创建圆形或者椭圆形
+ (instancetype)bezierPathWithOvalInRect:(CGRect)rect;
当传入的rect是一个正方形时,绘制的图像是一个内切圆;当传入的rect是一个长方形时,绘制的图像是一个内切椭圆。
UIColor color = [UIColor yellowColor];
[color set]; //设置线条颜色
UIBezierPath aPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 20, 100, 50)];
aPath.lineWidth = 2.0;
aPath.lineCapStyle = kCGLineCapRound; //线条拐角
aPath.lineJoinStyle = kCGLineCapRound; //终点处理
[aPath stroke];
- 使用UIBezierPath创建一段弧线
+ (instancetype)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;
center圆弧的中心点、radius半径、startAngle开始角度、endAngle结束角度、clockwise是否顺时针方向。
UIColor ***color = [UIColor yellowColor];
[color set];
UIBezierPath *aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 150) radius:radiuse startAngle:0 endAngle:radians(50) clockwise:YES];
aPath.lineWidth = 2.0;
aPath.lineCapStyle = kCGLineCapRound;
aPath.lineJoinStyle = kCGLineCapRound;
[aPath stroke];
- UIBezierPath虚线
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(20, 100)];
[path addLineToPoint:CGPointMake(20, 20)];
CGFloat dash[] = {2,2};
[path setLineDash:dash count:2 phase:0];//!!!
[[UIColor yellowColor] setStroke];
[path stroke];
- UIBezierPath还提供了贝塞尔曲线
UIColor color = [UIColor yellowColor];
[color set];
UIBezierPath aPath = [UIBezierPath bezierPath];
aPath.lineWidth = 1.0;
aPath.lineCapStyle = kCGLineCapRound;
aPath.lineJoinStyle = kCGLineCapRound;
[aPath moveToPoint:CGPointMake(20, 100)];
[aPath addQuadCurveToPoint:CGPointMake(120, 100) controlPoint:CGPointMake(10, 20)];
[aPath stroke];