有时候我们可能需要再界面上重点提示某些地方,例如镂空的提示效果,这个时候界面上遮盖蒙板但需要突出的地方需要镂空展示,这个时候我们需要用到蒙板功能,给layer的mask层一个新CAShapeLayer,并使用UIBezierPath绘制我们想要的图形,将绘制的图形设置给CAShapeLayer的path,来实现改变layer形状的效果。
上面镂空部分的源码:
//底部灰色的view
UIView *maskView = [[UIView alloc] initWithFrame:self.bounds];
maskView.backgroundColor = LS_COLORS_NEW_BLACK;
maskView.alpha = 0.7;
[self addSubview:maskView];
//贝塞尔曲线 画一个矩形
UIBezierPath *bpath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:0];
//矩形镂空的部分
CGRect ovalRect = CGRectMake(kSCREEN_WIDTH/3 - 10, (76 * WIDTH_RATIO)+64, kSCREEN_WIDTH/3+20, 70);
UIBezierPath *ovalPath = [[UIBezierPath bezierPathWithOvalInRect:ovalRect] bezierPathByReversingPath];
[bpath appendPath:ovalPath];
//椭圆
UIBezierPath *squarePath = [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(kSCREEN_WIDTH - 100, 64, 100, 40) cornerRadius:2.0]bezierPathByReversingPath];
[bpath appendPath:squarePath];
//创建一个CAShapeLayer 图层
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = bpath.CGPath;
//添加图层蒙板
maskView.layer.mask = shapeLayer;
首先绘制了一个与背景同等大小的UIBezierPath路径
UIBezierPath *bpath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:0];
然后绘制另外一个路径,即右上角正方形,其中bezierPathByReversingPath是反转内容的当前路径曲线路径的对象,将这个反转后的路径添加到上面绘制的路径中,即能将这部分的镂空出来
CGRect ovalRect = CGRectMake(kSCREEN_WIDTH/3 - 10, (76 * WIDTH_RATIO)+64, kSCREEN_WIDTH/3+20, 70);
UIBezierPath *ovalPath = [[UIBezierPath bezierPathWithOvalInRect:ovalRect] bezierPathByReversingPath];
[bpath appendPath:ovalPath];