Set Shadow on Bottom UIView only

Sonic Master picture Sonic Master · Mar 30, 2017 · Viewed 44.8k times · Source

I want to create bottom only shadow on UIView. Right now with this function, will create shadow in top, bottom, left, and right.

func setCardView(view : UIView){
    view.layer.masksToBounds = false
    view.layer.shadowOffset = CGSize(width: 0, height: 0)
    view.layer.shadowRadius = 2
    view.layer.shadowOpacity = 0.5
}

Is there anyway to only create shadow in the bottom? Any help would be appreciated. Thank you!

Answer

Elvin picture Elvin · Mar 30, 2017

I think the proper way of thinking of shadow is, the shadow belongs to the object, which is the button, the uiview, not just part of the side. Imagining there is a virtual light source. You can't really just create a shadow for one side.

With that being said, the shadow will always be the shadow of the view as a whole. However, you can change the shadow offset to make it towards to the bottom.

view.layer.shadowOffset = CGSize(width: 0, height: 3)

This means you want the light source shoot the light from top to make the shadow to the bottom. The reason you still see some shadow at the top is the shadow radius. which is to simulate the diffuse of the light. The more diffuse the light is, the softer the shadow will be so you will see top shadow still.

view.layer.shadowRadius = 1 or 0.5

try to reduce the radius also. it will give you a better visual result.

To understand umbra, penumbra and antumbra if you need, check out https://en.wikipedia.org/wiki/Umbra,_penumbra_and_antumbra