How do I create a UIView with a transparent circle inside (in swift)?

前端 未结 4 1414
一生所求
一生所求 2020-12-12 20:30

I want to create a view that looks like this: \"Goal

I figure what I need is a uiview with some sort of

4条回答
  •  孤街浪徒
    2020-12-12 21:11

    The above solution works great.

    Say if you are looking for mask with rectangle area here is the snippet below

    let fWidth = self.frame.size.width
    let fHeight = self.frame.size.height
    let squareWidth = fWidth/2
    let topLeft = CGPoint(x: fWidth/2-squareWidth/2, y: fHeight/2-squareWidth/2)
    let topRight = CGPoint(x: fWidth/2+squareWidth/2, y: fHeight/2-squareWidth/2)
    let bottomLeft = CGPoint(x: fWidth/2-squareWidth/2, y: fHeight/2+squareWidth/2)
    let bottomRight = CGPoint(x: fWidth/2+squareWidth/2, y: fHeight/2+squareWidth/2)
    let cornerWidth = squareWidth/4
    
    
    // Step 2
    let path = CGMutablePath()
    path.addRoundedRect(in: CGRect(x: topLeft.x, y: topLeft.y,
      width: topRight.x - topLeft.x, height: bottomLeft.y - topLeft.y),
     cornerWidth: 20, cornerHeight: 20)
    
    
    path.addRect(CGRect(origin: .zero, size: self.frame.size))
    // Step 3
    let maskLayer = CAShapeLayer()
    maskLayer.backgroundColor = UIColor.clear.cgColor
    maskLayer.path = path
    // For Swift 4.0
    maskLayer.fillRule = kCAFillRuleEvenOdd
    // For Swift 4.2
    //maskLayer.fillRule = .evenOdd
    // Step 4
    self.layer.mask = maskLayer
    self.clipsToBounds = true
    

    rectangle mask looks like this

提交回复
热议问题