使用UIBezierPath贝塞尔曲线配合CAShapeLayer抠图

##使用UIBezierPath贝塞尔曲线配合CAShapeLayer抠图app

###系统提供的UIBezierPath构造方法code

先来看看构造方法列表,以及构造出来的形状,具体详见后面的示例及图片。图片

一、矩形it

+ (instancetype)bezierPathWithRect:(CGRect)rect;方法

二、内切圆,即椭圆im

+ (instancetype)bezierPathWithOvalInRect:(CGRect)rect;img

三、圆角矩形di

+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect cornerRadius:(CGFloat)cornerRadius; // rounds all corners with the same horizontal and vertical radiusview

,可设置圆角的半径vi

四、部分圆角的矩形

+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;

* rect: 矩形frame
* corners: 要画成圆角的部位
* cornerRadii: 圆角的大小

五、圆弧

+ (instancetype)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;

* center: 圆心坐标
* radius: 圆的半径
* startAngle: 起点角度
* endAngle: 终点角度
* clockwise: 是否顺时针

六、指定路径

+ (instancetype)bezierPathWithCGPath:(CGPathRef)CGPath;

###配合CAShapeLayer

利用CAShapeLayer,能画出各类形状,只须要将UIBezierPath的CGPath赋予CAShapeLayer的path便可。

####代码示例

// 要抠的透明区域位置
CGRect cutFrame = CGRectMake(0, 200, self.view.bounds.size.width, 400);
UIBezierPath *cutPath1 = [UIBezierPath bezierPathWithRect:cutFrame];//图1 - 普通矩形
/*
 UIBezierPath *cutPath2 = [UIBezierPath bezierPathWithRoundedRect:cutFrame cornerRadius:20];//图2 - 圆角为20的圆角矩形
 UIBezierPath *cutPath3 = [UIBezierPath bezierPathWithRoundedRect:cutFrame byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];//图3 - 左上和右上为圆角20的部分圆角矩形
 UIBezierPath *cutPath4 = [UIBezierPath bezierPathWithOvalInRect:cutFrame];//图4 - 内切圆(椭圆)
 */

// 要抠透明区域的原图
CGRect viewFrame = self.view.bounds;
UIBezierPath *viewPath = [UIBezierPath bezierPathWithRect:viewFrame];

// 调用bezierPathByReversingPath,进行路径反转,才会产生抠图效果
[viewPath appendPath:[cutPath1 bezierPathByReversingPath]];

// 配合CAShapeLayer,调用layer(此layer必须是第一层,不能嵌套)的setMask方法设置遮罩层
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = viewPath.CGPath;
[self.view.layer setMask:shapeLayer];

####效果图

#####图1 - 普通矩形

General preferences pane

#####图2 - 圆角为20的圆角矩形

General preferences pane

#####图3 - 左上和右上为圆角20的部分圆角矩形

General preferences pane

#####图4 - 内切圆(椭圆)

General preferences pane

相关文章
相关标签/搜索