新手引导大多数app都会有这个功能,然而据了解蛮多就是直接贴张图片上面就搞定了.
额,这样做确实简单,可是这样好Low而且做出来的效果不好,那我们来用逼格高点的镂空方式实现:
先来一个简单的效果图:
实现起来也很简单,主要分3个步骤:
1.创建一个镂空的路径:
UIBezierPath 有个原生的方法- (void)appendPath:(UIBezierPath *)bezierPath, 这个方法作用是俩个路径有叠加的部分则会镂空.
这个方法实现原理应该是path的FillRule 默认是FillRuleEvenOdd(CALayer 有一个fillRule属性的规则就有kCAFillRuleEvenOdd), 而EvenOdd 是一个奇偶规则,奇数则显示,偶数则不显示.叠加则是偶数故不显示.
2.创建CAShapeLayer 将镂空path赋值给shapeLayer
3.将shapeLayer 设置为背景视图的Mask
UIView *backgroundView = [[UIView alloc] init];
backgroundView.frame = self.view.bounds;
backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
[self.view addSubview:backgroundView];
// 创建一个全屏大的path
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.view.bounds];
// 创建一个圆形path
UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.view.center.x, self.view.center.y - 25)
radius:50
startAngle:0
endAngle:2 * M_PI
clockwise:NO];
[path appendPath:circlePath];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = path.CGPath;
backgroundView.layer.mask = shapeLayer;
顺便提下,在实际开发中可能遇到这种需求,当tableView 滑动到某个位置的时候才显示新手引导.
这时候就需要将tableView上的坐标转化为相对于屏幕的坐标. 可用原生的方法:
-
(CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
-
(CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;