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
There is a lot information on the internet about layers and working with them. As for layers with transparent centre, there is good discussion with examples.
CALayer with transparent hole in it
I have a simple view (left side of the picture) and i need to create some kind of overlay (right side of the picture)…
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.
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
Another way is using an auxiliary layer as mask. First a shape layer with specified path, position, fillColor is created and then an aux layer(mask) is created.
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.
Now you know two simple ways to create layers with a transparent centre and how to add shadow to them. That’s it. Have a nice day.