Pragmatically creating UIView Mask

时间:2018-04-18 18:06:18

标签: ios swift uiview

I have a UIView, which has a user selected number of circles (5) and a gradient color scheme (Top image) That part was easy

The circles are just additional subViews of the master UIView with black borders and the master UIView has a Red border

How can one create the cyan blue mask seen on the bottom image ? With Code ?

Thanks in advance

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在主UIView的图层上添加CAShapeLayer,如下所示:

func addMask(view: UIView) {
  // first, lets create UIBezierPath of rounded rect shape
  let border = view.layer.borderWidth
  let radius = view.layer.cornerRadius
  let frame = view.bounds.insetBy(dx: border, dy: border)
  let path = UIBezierPath(roundedRect: frame, cornerRadius: radius)

  // then iterate over circle subviews and add corresponding path to rounded rect
  for subview in view.subviews {
    let circlePath = UIBezierPath(ovalIn: subview.frame)
    path.append(circlePath)
  }

  // now declare a CAShapeLayer and set rounded rect & co as its path
  let mask = CAShapeLayer()
  mask.path = path.cgPath
  mask.fillColor = UIColor.cyan.cgColor

  // this makes circles to appear as cutouts
  mask.fillRule = kCAFillRuleEvenOdd

  view.layer.addSublayer(mask)
}

// use the function like this
addMask(view: masterView)