使用 贝塞尔曲线绘制cell 圆角

2021-05-08  本文已影响0人  xyZHua
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
// section row 个数
NSInteger sectionCount = [tableView numberOfRowsInSection:indexPath.section] - 1;
// 显示的cell 点击区域,12为距离左右边距
  CGRect bounds = CGRectInset(cell.bounds, 12, 0); 
  // 2.再盖一个 mask
  CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];// 用于蒙板
  // section 只有一个时。
  if (indexPath.row == 0 && indexPath.row == sectionCount) {
      [maskLayer setPath:[UIBezierPath bezierPathWithRoundedRect:bounds cornerRadius:radius].CGPath];   
  } else if (indexPath.row == 0) {
// 第一个 row 只有顶部圆角 ---> UIRectCornerTopLeft | UIRectCornerTopRight
      [maskLayer setPath:[UIBezierPath bezierPathWithRoundedRect:bounds
                                          byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)                                          cornerRadii:CGSizeMake(radius, radius)].CGPath];
      } else if (indexPath.row == sectionCount) {
// 最后一个 row 只有底部圆角 --> UIRectCornerBottomLeft | UIRectCornerBottomRight
          [maskLayer setPath:[UIBezierPath bezierPathWithRoundedRect:bounds
                                                   byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight)
                                                         cornerRadii:CGSizeMake(radius, radius)].CGPath]; 
      } else {
// 中间 row 无圆角
          UIBezierPath *path = [UIBezierPath bezierPathWithRect:bounds];
          [maskLayer setPath:path.CGPath];
      }
      // 2.mask
      [cell setMaskView:[[UIView alloc] initWithFrame:cell.bounds]];
      [cell.maskView.layer insertSublayer:maskLayer atIndex:0];
      [cell.maskView.layer setMasksToBounds:YES];
      [cell setClipsToBounds:YES];
}
上一篇下一篇

猜你喜欢

热点阅读