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

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.

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

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.

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


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.




Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ace Rodstin

Ace Rodstin

More from Medium

Every iOS developer should know these Xcode tricks

Swift — Cocoapods Usage

Learning Swift

Whats new in swift 5.5