在工程中有一些需求需要设置部分遮罩,如二维码扫描区域的图形绘画,类似于头像圆角等,这时候变需要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];
}
网友评论