UIKit: View Shadow
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 😉
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:
- I set the
cornerRadiusproperty as described in my previous post UIKit Rounded Views.
- I set shadow opacity that is a value from 0 to 1 to be applied to the shadow color.
- I set the shadow color.
- 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.
- 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
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.
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.