在工程中有一些需求需要設(shè)置部分遮罩,如二維碼掃描區(qū)域的圖形繪畫,類似于頭像圓角等,這時(shí)候變需要CAShapeLayer,UIBezierPath等進(jìn)行繪圖
簡(jiǎn)單的代碼如下

Simulator Screen Shot - iPhone 6s - 2018-02-24 at 14.25.31.png
//設(shè)置背景色為白色
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];
}