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

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

    Even though there is an answer, i'd like to share my way:

    // Let's say that you have an outlet to the image view called imageView
    // Create the white view 
    let whiteView = UIView(frame: imageView.bounds) 
    let maskLayer = CAShapeLayer() //create the mask layer
    
    // Set the radius to 1/3 of the screen width
    let radius : CGFloat = imageView.bounds.width/3 
    
    // Create a path with the rectangle in it.
    let path = UIBezierPath(rect: imageView.bounds)
    // Put a circle path in the middle
    path.addArcWithCenter(imageView.center, radius: radius, startAngle: 0.0, endAngle: CGFloat(2*M_PI), clockwise: true)
    
    // Give the mask layer the path you just draw
    maskLayer.path = path.CGPath
    // Fill rule set to exclude intersected paths
    maskLayer.fillRule = kCAFillRuleEvenOdd
    
    // By now the mask is a rectangle with a circle cut out of it. Set the mask to the view and clip.
    whiteView.layer.mask = maskLayer
    whiteView.clipsToBounds = true
    
    whiteView.alpha = 0.8
    whiteView.backgroundColor = UIColor.whiteColor()
    
    //If you are in a VC add to the VC's view (over the image)
    view.addSubview(whiteView)    
    // Annnnnd you're done.
    

提交回复
热议问题