UIBezierPath详解:
使用UIBezierPath类可以创建基于矢量的路径,这个类在UIKit中。此类是Core Graphics框架关于path的一个封装。使用此类可以定义简单的形状,如椭圆或者矩形,或者有多个直线和曲线段组成的形状。
UIBezierPath对象是CGPathRef数据类型的封装。path如果是基于矢量形状的,都用直线和曲线段去创建。我们使用直线段去创建矩形和多边形,使用曲线段去创建弧(arc),圆或者其他复杂的曲线形状。每一段都包括一个或者多个点,绘图命令定义如何去诠释这些点。每一个直线段或者曲线段的结束的地方是下一个的开始的地方。每一个连接的直线或者曲线段的集合成为subpath。一个UIBezierPath对象定义一个完整的路径包括一个或者多个subpaths。
/* 根据一个Rect画一个椭圆曲线 Rect为正方形时画的是一个圆 */
+ (instancetype)bezierPathWithRect:(CGRect)rect;
/* 根据一个Rect画一个圆角矩形曲线 (Radius:圆角半径) 当Rect为正方形时且Radius等于边长一半时画的是一个圆 */
+ (instancetype)bezierPathWithOvalInRect:(CGRect)rect;
/* 根据一个Rect画一个圆角矩形曲线 当Rect为正方形时且Radius等于边长一半时画的是一个圆 */
+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect cornerRadius:(CGFloat)cornerRadius;
typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
UIRectCornerTopLeft = 1 << 0,
UIRectCornerTopRight = 1 << 1,
UIRectCornerBottomLeft = 1 << 2,
UIRectCornerBottomRight = 1 << 3,
UIRectCornerAllCorners = ~0UL
};
/* 根据一个Rect针对四角中的某个或多个角设置圆角 */
+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;
/* 以某个中心点画弧线
* @param center 指定了圆弧所在正圆的圆心点坐标
* @param radius 指定了圆弧所在正圆的半径
* @param startAngle 指定了起始弧度位置 注意: 起始与结束这里是弧度
* @param endAngle 指定了结束弧度位置
* @param clockwise 指定了绘制方向,以时钟方向为判断基准 */
+ (instancetype)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;
/* 根据CGPath创建并返回一个新的UIBezierPath对象 */
+ (instancetype)bezierPathWithCGPath:(CGPathRef)CGPath;
可以使用UIBezierPath来绘制圆环
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(backView.frame.size.width/2, backView.frame.size.height/2) radius:radius startAngle:(0) endAngle:2*M_PI clockwise:clockWise];
CAShapeLayer *layer = [[CAShapeLayer alloc] init];
//圆环的宽度
layer.lineWidth = 10;
//圆环的颜色
layer.strokeColor = [UIColor redColor].CGColor;
//背景填充色
layer.fillColor = [UIColor clearColor].CGColor;
//设置半径
CGFloat radius = _backView.frame.size.width/2-5;
//按照顺时针方向
BOOL clockWise = true;
//初始化一个路径
layer.path = [path CGPath];
[backView.layer addSublayer:layer];
给UIView顶部加圆角
CGSize size = [backView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGRect newFrame = CGRectMake(0, 0, size.width, size.height);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newFrame byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = newFrame;
maskLayer.path = path.CGPath;
backView.layer.mask = maskLayer;