See-through UIViews

Using CAShapeLayer and UIBezierPath to mask UIView holes.

Bruno Muniz
Swift2Go

--

Photo by Majid Gheidarlou on Unsplash

In the last couple of days I’ve been working on a QR code scanner feature (as you can probably tell by the topic of my last article) and I’ve stumbled upon a situation where I needed a semi-transparent overlay view which is completely transparent in the middle. In other words: a squared hole into an opaque view (or in this case semi-opaque).

CAShapeLayer + UIBezierPath will do the trick.

The trick is pretty straightforward — basically we need to get the path from our overlayView using UIBezierPath(rect: overlayView.bounds), then set fillRule from our CAShapeLayer to .evenOdd and then append the path of the view we want to crop. We could either do point/point…line/line using path.append or we can simply add a subvview to the overlayView with the size we want to crop and then append its bounds to the path.

--

--