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

后端 未结 5 2113
盖世英雄少女心
盖世英雄少女心 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:18

    Here is sample code for how you can make a circle Mask for a UIView:

    let sampleView = UIView(frame: UIScreen.mainScreen().bounds)
    let maskLayer = CALayer()
    maskLayer.frame = sampleView.bounds
    let circleLayer = CAShapeLayer()
    //assume the circle's radius is 100
    circleLayer.frame = CGRectMake(sampleView.center.x - 100, sampleView.center.y - 100, 200, 200)
    let circlePath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 200, 200))
    circleLayer.path = circlePath.CGPath
    circleLayer.fillColor = UIColor.blackColor().CGColor
    maskLayer.addSublayer(circleLayer)
    
    sampleView.layer.mask = maskLayer
    

    Here is what I made in the playground:

    enter image description here

提交回复
热议问题