Skip to content

Instantly share code, notes, and snippets.

@markedwardmurray
Created September 28, 2017 23:13
Show Gist options
  • Save markedwardmurray/8306b1d82e4a30833424b84551128f29 to your computer and use it in GitHub Desktop.
Save markedwardmurray/8306b1d82e4a30833424b84551128f29 to your computer and use it in GitHub Desktop.
Multiple cutouts
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
lazy var hello: UILabel = {
let hello = UILabel()
hello.frame = CGRect(x: 50, y: 200, width: 50, height: 50)
hello.text = "Hello"
hello.textColor = .black
hello.textAlignment = .center
return hello
}()
lazy var world: UILabel = {
let world = UILabel()
world.frame = CGRect(x: 150, y: 200, width: 50, height: 50)
world.text = "World"
world.textColor = .black
world.textAlignment = .center
return world
}()
lazy var bam: UILabel = {
let bam = UILabel()
bam.frame = CGRect(x: 250, y: 200, width: 50, height: 50)
bam.text = "!"
bam.textColor = .black
bam.textAlignment = .center
return bam
}()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
view.addSubview(hello)
view.addSubview(world)
view.addSubview(bam)
self.view = view
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let cutoutView = CutoutView()
cutoutView.frame = view.frame
cutoutView.cutoutPaths = [
circularCutoutPath(hello),
circularCutoutPath(world),
circularCutoutPath(bam)
]
view.addSubview(cutoutView)
}
func circularCutoutPath(_ view: UIView) -> UIBezierPath {
let circlePath = UIBezierPath(arcCenter: view.center, radius: view.frame.width/2, startAngle: CGFloat(-rad(90)), endAngle: CGFloat(rad(360-90)), clockwise: true)
return circlePath
}
}
func rad(_ degrees: Double) -> Double {
return degrees * .pi / 180.00
}
class CutoutView: UIView {
var fillColor: UIColor = UIColor.black.withAlphaComponent(0.8) {
didSet {
setNeedsDisplay()
}
}
var cutoutPaths: [UIBezierPath] = [] {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
layer.sublayers?.removeAll()
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.fillColor = fillColor.cgColor
maskLayer.fillRule = kCAFillRuleEvenOdd
let path = UIBezierPath(rect: bounds)
for cutoutPath in cutoutPaths {
path.append(cutoutPath)
}
maskLayer.path = path.cgPath
layer.mask = maskLayer
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment