Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw shadow only from 3 sides of UIView

Tags:

I've successfully implemented drawing a shadow around my UIView like this:

block1.layer.masksToBounds = NO; block1.layer.shadowOffset = CGSizeMake(0, 0); block1.layer.shadowRadius = 1; block1.layer.shadowOpacity = 0.7; 

What now happens is I have a rectangular UIView and i would like to draw the shadow around it three sides, leaving the bottom side of it without the shadow.

I know that I have to specify the block1.layer.shadowPath by creating a new UIBezierPath but I'm not sure how to do it.

Obviously, setting layer.shadowOffset won't do the trick for me.

Thanks in advance!

like image 270
Sergey Grischyov Avatar asked Mar 29 '13 13:03

Sergey Grischyov


People also ask

How do I add inner shadow to UIView with rounded corners?

Add subview with the same color which will be centered on the parent and will be with several pixels smaller. Like this you will have space from each side of the parent. On the parent turn on clipping subviews and add shadow to the inner view. Like this, you can have an inner shadow.

What is shadow offset?

ShadowOffset is a CGSize representing how far to offset the shadow from the path. The default value of this property is (0.0, -3.0).


1 Answers

I know you say setting layer.shadowOffset won't work for you, but you are allowed to put in negative values so setting it layer.shadowOffset = CGSizeMake(0.0, -2.0) would come close to the effect you're looking for but of course I expect you want it to be even on the three sides.

So here we go with layer.shadowPath!

UIView *block1 = [[UIView alloc] initWithFrame:CGRectMake(32.0, 32.0, 128.0, 128.0)]; [block1 setBackgroundColor:[UIColor orangeColor]]; [self.view addSubview:block1];  block1.layer.masksToBounds = NO; block1.layer.shadowOffset = CGSizeMake(0, 0); block1.layer.shadowRadius = 1; block1.layer.shadowOpacity = 0.7;  UIBezierPath *path = [UIBezierPath bezierPath];  // Start at the Top Left Corner [path moveToPoint:CGPointMake(0.0, 0.0)];  // Move to the Top Right Corner [path addLineToPoint:CGPointMake(CGRectGetWidth(block1.frame), 0.0)];  // Move to the Bottom Right Corner [path addLineToPoint:CGPointMake(CGRectGetWidth(block1.frame), CGRectGetHeight(block1.frame))];  // This is the extra point in the middle :) Its the secret sauce. [path addLineToPoint:CGPointMake(CGRectGetWidth(block1.frame) / 2.0, CGRectGetHeight(block1.frame) / 2.0)];  // Move to the Bottom Left Corner [path addLineToPoint:CGPointMake(0.0, CGRectGetHeight(block1.frame))];  // Move to the Close the Path [path closePath];  block1.layer.shadowPath = path.CGPath; 

And to give you an idea of whats going on, here is the actual shadow path you just drew :)

enter image description here

Its possible to just shift that extra middle point before or after the other lines to choose which side will be omitted.

like image 140
Ryan Poolos Avatar answered Nov 14 '22 15:11

Ryan Poolos