Match Your iOS Shadow Spread and Blur to Match Sketch

Originally Posted on medium.com/better-programming/how-to-match-..

Recently, I’ve designed one of the screens of my project using the Sketch application. I’ve given a shadow property to the element with blur and spread.

But when I try to replicate the same shadow effect in the iOS application, it doesn’t quite work. That’s because the spread property does not exist in the CALayer class of the CoreAnimation framework. Also, blur and shadowRadius don't produce the same effect as the Sketch app.

The following are the results of setting a shadow offset of (10, 10) and a blur radius of 10 with spread value of 3 in Sketch and the iOS application.

image.png

image.png

As you can see, there is a clear visual difference between the output of the Sketch application and the iOS application. I used the code snippet below to generate the shadow in the iOS application using Swift:

After doing some research, I found that dividing the Sketch application blur value by the iOS screen scale factor for the shadow radius will work. Based on that, I’ve modified my code as below (Note: The blur value set to 3 in the sketch):

image.png

image.png

Let’s create a new extension on CALayer by combining all six of the Sketch shadow properties to a UIView’s layer as below:

image.png

Now you can easily achieve the same result as the Sketch application by using the extension above:

shadowView.layer.applySketchShadow(x: 10, y: 10, blur: 3, spread: 3)

image.png

image.png

Notes

  • The spread radius increases/decreases the size of the shadow. A positive value increases the size of the shadow and a negative value decreases the size of the shadow.
  • When using a non-zero spread, it hardcodes a path based on the bounds of the CALayer. If the layer's bounds ever change, you'd want to call the applySketchShadow() method again.
  • Don’t forget to check out this GitHub page. From there, you can find the extension written on CALayer. Also, it consists of a few more extensions that will be useful in our application.

Reference

Questions?

Please feel free to comment below if you have any questions.

Thanks for reading!

You can find me on:

Twitter | LinkedIn | GitHub | Medium | HackerRank | LeetCode | Stack Overflow

Did you find this article valuable?

Support MILAN PANCHAL by becoming a sponsor. Any amount is appreciated!