Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 view below to make a tutorial for my app. I know how to create a circular shape but i don't know how to cut it out in a view. I need a complete example on how to do it please. Thanks in advance

Image

like image 506
LamBronx Avatar asked Apr 15 '15 10:04

LamBronx


1 Answers

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.
like image 87
Dănuț Mihai Florian Avatar answered Nov 13 '22 14:11

Dănuț Mihai Florian