iOS Mask属性的详细介绍及应用实例

2020-01-18 17:22:58王振洲
iOS,Mask属性,Mask属性详解,Mask属性具体应用

实现起来也很简单,主要分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;

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到IOS开发频道。