6

I have the same problem as the link here: Can't add a corner radius and a shadow

if I put maskToBounds = YES, I get round corners, but no shadow If I put maskToBounds = NO, I get shadow, but no round corners.

Then I followed the instruction in that link above , setting maskToBounds = NO, " but rather set the corner radius and set the bezier path of the shadow with a rounded rect. Keep the radius of the two the same ". But then, I don't get round corners, nor did I get any shadow! (i.e. Square Image without Shadow) Could you please help me out of this? I don't know what did I do wrong. Thanks in advance.

self.userImageView.backgroundColor = [UIColor redColor]; 
self.userImageView.clipsToBounds = NO; 
self.userImageView.contentMode = UIViewContentModeCenter; 
self.userImageView.layer.masksToBounds = NO; 

self.userImageView.layer.borderWidth = 1; 
self.userImageView.layer.borderColor = [[UIColor grayColor] CGColor]; 

self.userImageView.layer.shadowOpacity = 1; 
self.userImageView.layer.shadowColor = [[UIColor blackColor] CGColor]; 
self.userImageView.layer.shadowRadius = 8.0f; 
self.userImageView.layer.shadowOffset = CGSizeMake(-3, 0);
self.userImageView.layer.shouldRasterize = YES; 

self.userImageView.layer.shadowPath = [[UIBezierPath bezierPathWithRoundedRect:[self.userImageView bounds] cornerRadius:10.0f] CGPath]; 

[self addSubview:self.userImageView]; 
Community
  • 1
  • 1
John
  • 2,672
  • 2
  • 23
  • 29

1 Answers1

20

Unfortunately, I don't think UIImageView supports rounded corner and shadow at the same time.

You can, however, make the shadow in the UIImageView's super view.

CGFloat cornerRadius = 3.0

UIView *container = [[UIView alloc] initWithFrame:aRect];
container.layer.shadowOffset = CGSizeMake(0, 0);
container.layer.shadowOpacity = 0.8;
container.layer.shadowRadius = 5.0;
container.layer.shadowColor = [UIColor redColor].CGColor;
container.layer.shadowPath = [[UIBezierPath bezierPathWithRoundedRect:container.bounds cornerRadius:cornerRadius] CGPath];

self.userImageView.layer.cornerRadius = cornerRadius;
self.userImageView.layer.masksToBounds = YES;
self.userImageView.frame = container.bounds;
[container addSubview:self.userImageView];
[self addSubview:container];
Joseph Lin
  • 3,324
  • 1
  • 29
  • 39
  • I think your approach will work, I'll try it soon. Thanks for the answer. It's been quite a long time since I posted the question, I was very excited to see an answer. – John Oct 19 '12 at 19:06
  • aRect is where you want your imageView to be (i.e. imageView's frame when without the container.) – Joseph Lin Jan 04 '14 at 02:22
  • Shadow radius is *blur*, not corner radius on the shadow. – Dustin Jan 04 '17 at 01:36