How to create a layer with a shadow and a transparent centre

Hello. Sometimes it necessary to create hollow shapes and cast a shadow from it. Wealthy Swift library grants to developers several way to achieve this. As always, each approach has strengths and weakness. This topic brings a review of the most easiest way to create hollow layer and offers alternative solution.

Easiest way to reach the goal

Shortly, all you need is create CAShapeLayer with two paths and set usesEvenOddFillRule as true. Everything is as usual: a layer is created, then path, position, fillColor and fillRule is set.

As a result, you have a shape with transparent centre.

But what if you want to add the shadow for this layer? Attempting to add a shadow will result in a black hole in the centre.

A black hole.

This is because usually the path of the shadow is set in the same way as the shape (for example a circle).

Alternative way to create hollow layer and cast the shadow from it

Notice that fillColor, strokeColor and lineWidth, are set for the mask layer. You set the fillColor so that the centre is transparent. Stroke color and line width are set to display the rest of the shape layer. The line width should be set a little more than the edges of a shape layer. Otherwise, the shadow that is being added will be cropped. To be more precise, you need to set the extra line width equal to shadow radius so as not to cut the shadow.

A circles with a transparent centre(red, yellow, green) and shadow(red, green).