Software Development Blog


How to solve the masksToBounds problem with the shadow of UIView?

Github project

In the previous post, I showed how to add different properties like a shadow, border, image, cornerRadius to CALayer. All layers have masksToBounds property. If masksToBounds = true - It will clip all layers that are bigger than their superlayer. And this is a useful property. As we know the shadow is an element out of view box. And it will be clipped with masksToBounds = true. And it is a problem! Another problem is image. We can't clip image if masksToBounds = false. So it is impossible to create an image like bellow with the only view.layer property

It is difficult because of image needs masksToBounds = true, and red shadow needs masksToBounds = false.

In the code above, we have a default layer setup - cornerRadius, shadow, and border. We need view.layer.masksToBounds = false, shadow effect will be invisible if masksToBounds will be equal to true.

The trick in the image layer. As we can't set masksToBounds for the parent layer, we can create another layer only for image and mask it. And it is a cheap trick to have a few layers with different masksToBounds value.

In this post, you can find more info about CALayer.

Recent Posts

What are UUID identifiers in Swift?


How to use Comparable protocol