UIKit: View Shadow

“A glossy red apple on a wooden surface” by Michał Grosicki on Unsplash

Last time we talked about how to get a view’s corners rounded. Today, as promised, I will show you how to use the layer.shadowX properties in order to make a view look like a Card and to obtain other cool effects.

Let’s start off with the simple and the never-gets-old Card View. I know you need this 😉

Card View
myCard.layer.cornerRadius = 10
myCard.layer.shadowOpacity = 1
myCard.layer.shadowColor = UIColor(named: "Swift Orange")!.cgColor
myCard.layer.shadowRadius = 4
myCard.layer.shadowOffset = CGSize(width: 4, height: 4)

The code is self-explanatory:

  1. I set the cornerRadius property as described in my previous post UIKit Rounded Views.
  2. I set shadow opacity that is a value from 0 to 1 to be applied to the shadow color.
  3. I set the shadow color.
  4. I set the shadow radius that represents the blur radius. If you are lazy to read like me you just need to know that the higher this value the more blurred the image will be. If you are eager to learn, click here.
  5. Finally I set the offset which is the offset of the shadow from the layer expressed in points.

Note: to make the shadow visible, do not set to true the layer‘s property masksToBounds otherwise it will be clipped.

This is not over…there is one more shadow attribute that we can leverage to make some cool effects: shadowPath. Let’s see how we can make a view like it is floating on our device’s screen.

Custom Shadow
let cardWidth = myCard.frame.width
let cardHeight = myCard.frame.height
let distanceFromCard = 15
myCard.layer.cornerRadius = cardWidth * 0.5
myCard.layer.shadowOpacity = 0.1
myCard.layer.shadowRadius = 2
myCard.layer.shadowColor = UIColor.black.cgColor
myCard.layer.shadowOffset = CGSize(width: 0, height: cardHeight)
let path = CGPath(ellipseIn: CGRect(x: 0, y: distanceFromCard, width: Int(cardWidth), height: Int(cardHeight * 0.1)), transform: nil)
myCard.layer.shadowPath = path

Same as the previous example but instead of using the default shadow shape, I used an ellipse. Very simple.




Previous Posts

  1. UIKit Rounded Views