Swift - How to create a view with a shape cropped in it

后端 未结 5 2119
盖世英雄少女心
盖世英雄少女心 2021-01-04 10:00

I\'m trying to achieve the result shown in the image using swift 1.2 and xcode 6.

Basically I want to create a view with a shape cut in it to be able to see the the

5条回答
  •  暖寄归人
    2021-01-04 10:30

        //assume you create a UIImageView and content image before execute this code
      let sampleMask = UIView()
        sampleMask.frame = self.view.frame
        sampleMask.backgroundColor =  UIColor.black.withAlphaComponent(0.6)
        //assume you work in UIViewcontroller
        self.view.addSubview(sampleMask)
        let maskLayer = CALayer()
        maskLayer.frame = sampleMask.bounds
        let circleLayer = CAShapeLayer()
        //assume the circle's radius is 150
        circleLayer.frame = CGRect(x:0 , y:0,width: sampleMask.frame.size.width,height: sampleMask.frame.size.height)
        let finalPath = UIBezierPath(roundedRect: CGRect(x:0 , y:0,width: sampleMask.frame.size.width,height: sampleMask.frame.size.height), cornerRadius: 0)
        let circlePath = UIBezierPath(ovalIn: CGRect(x:sampleMask.center.x - 150, y:sampleMask.center.y - 150, width: 300, height: 300))
        finalPath.append(circlePath.reversing())
        circleLayer.path = finalPath.cgPath
        circleLayer.borderColor = UIColor.white.withAlphaComponent(1).cgColor
         circleLayer.borderWidth = 1
        maskLayer.addSublayer(circleLayer)
    
        sampleMask.layer.mask = maskLayer
    

提交回复
热议问题