App-it.dk

Objective-C, iOS and Web.

UIView With Shadow and Rounded Corners

If you want to create a UIView in your iOS app, that both have a drop shadow, and rounded corners, you have to do some magic with the view layers. In order to make rounded corners, the view and/or layer will have to set maskToBounds = YES, which will cause a shadow in the same layer to disappear, as the shadow needs to go beyond than the view bounds.

To achieve both a drop shadow and rounded corners, a solution could be to create 2 different layers and added them to your view. The following code assumes that we’re in a UIView object/class:

Creating the shadow layer
1
2
3
4
5
6
7
8
9
CALayer shadowLayer = [CALayer layer];
shadowLayer.shadowOffset = CGSizeMake(0, 3);
shadowLayer.shadowRadius = 8.0f;
shadowLayer.shadowOpacity = 0.8f;
shadowLayer.shadowColor = [UIColor blackColor].CGColor;
shadowLayer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
shadowLayer.frame = self.layer.bounds;
//Add the shadow layer to the existing view layer.
[self.layer addSublayer:shadowLayer];

Next we create the layer that will create the rounded corners on the view:

Creating a layer for rounding the corners
1
2
3
4
5
6
CALayer cornerLayer = [CALayer layer];
cornerLayer.cornerRadius = 5.0f;
cornerLayer.frame = shadowLayer.bounds;
cornerLayer.masksToBounds = YES;
//The shadow layer we just created.
[shadowLayer addSublayer:cornerLayer];

This should create the wanted effect of having both a shadow and rounded corners on the UIView.

Comments