关于利用CAShapeLayer设置遮罩和图形,贝塞尔曲线的傻瓜运用

在工程中有一些需求需要设置部分遮罩,如二维码扫描区域的图形绘画,类似于头像圆角等,这时候变需要CAShapeLayer,UIBezierPath等进行绘图
简单的代码如下
Simulator Screen Shot - iPhone 6s - 2018-02-24 at 14.25.31.png
//设置背景色为白色
self.view.backgroundColor = [UIColor whiteColor];
//绘制200*200的方框
[self setCropRect:CGRectMake((self.view.bounds.size.width-200)/2,
                                 (self.view.bounds.size.height-200)/2, 200, 200)];

- (void)setCropRect:(CGRect)cropRect{
    _testShaplayer= [[CAShapeLayer alloc] init];
    //绘制两条path
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, cropRect);
    CGPathAddRect(path, nil, self.view.bounds);
    //填充两条path的非交集
    [_testShaplayer setFillRule:kCAFillRuleEvenOdd];
    [_testShaplayer setPath:path];
    //颜色是黑色透明度0.6
    [_testShaplayer setFillColor:[UIColor blackColor].CGColor];
    [_testShaplayer setOpacity:0.6];
    
    
    [_testShaplayer setNeedsDisplay];
    
    [self.view.layer addSublayer:_testShaplayer];
    
}
Simulator Screen Shot - iPhone 6s - 2018-02-24 at 14.25.05.png
- (void)configRoundShape {
    self.view.backgroundColor = [UIColor whiteColor];
    _testShaplayer = [[CAShapeLayer alloc]init];
    //绘制贝塞尔曲线
    UIBezierPath *roundPath = [UIBezierPath bezierPathWithArcCenter:self.view.center radius:self.view.bounds.size.width/2 startAngle:0.0 endAngle:M_PI*2 clockwise:YES];
    UIBezierPath *rectPath = [UIBezierPath bezierPathWithRect:self.view.bounds];
    [roundPath appendPath:rectPath];
    //同样取非交集绘制
    [_testShaplayer setFillRule:kCAFillRuleEvenOdd];
    [_testShaplayer setPath:roundPath.CGPath];
    [_testShaplayer setFillColor:[UIColor blackColor].CGColor];
    [_testShaplayer setOpacity:0.6];
    
    [_testShaplayer setNeedsDisplay];
    
    [self.view.layer addSublayer:_testShaplayer];
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言:关于贝塞尔曲线与CAShapeLayer的学习 学习Demo演示: 贝塞尔曲线简单了解 使用UIBezier...
    麦穗0615阅读 17,946评论 18 149
  • 目录: 主要绘图框架介绍 CALayer 绘图 贝塞尔曲线-UIBezierPath CALayer子类 补充:i...
    Ryan___阅读 1,719评论 1 9
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,267评论 4 61
  • 假性亲密关系——你以为很近,其实你们很远 原文:微信-在假性亲密关系中逃避真的亲密感? 真正的亲密关系是你与另一个...
    relyingon阅读 1,256评论 0 4
  • 随着人们物质文化生活的提高,大家慢慢的开始追求精神上面的满足,可仍然还有一部分人对于“吃”——念念不忘,下面就...
    独自上路阅读 294评论 3 2