1

I am trying to give corner and shadow to a image at the same time. If I remove but I cant display shadow. I removed masksToBonds but then I lost corners. How to fix that?

_iconView.image = [UIImage imageNamed:cellObject.imageName];

_iconView.layer.cornerRadius = 30.0f;
_iconView.clipsToBounds = YES;

_iconView.layer.shadowRadius = 3.0f;
_iconView.layer.shadowColor = [UIColor blackColor].CGColor;
_iconView.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
_iconView.layer.shadowOpacity = 0.5f;
_iconView.layer.masksToBounds = NO;
rmaddy
  • 314,917
  • 42
  • 532
  • 579
birdcage
  • 2,638
  • 4
  • 35
  • 58
  • Check this https://stackoverflow.com/questions/40887532/how-to-give-an-imageview-in-swift3-0-1-shadow-at-the-same-time-with-rounded-corn – Abdelahad Darwish Aug 22 '17 at 13:59
  • That's swift answer. – birdcage Aug 22 '17 at 14:00
  • Possible duplicate of [UIView with rounded corners and drop shadow?](https://stackoverflow.com/questions/4754392/uiview-with-rounded-corners-and-drop-shadow) – DonMag Aug 22 '17 at 14:20
  • @birdcage no, it is an iOS answer. The answer is the same whether it is written in Swift or Objective-C. If you can’t translate between YES and true then that is a whole other problem that StackOverflow can’t help with. – Fogmeister Aug 22 '17 at 14:55

1 Answers1

0

You can set the shadowPath attribute to track that of the iconView path, and set its corner radius also, like so:

UIImageView * iv = [UIImageView new];
iv.frame = CGRectMake(0, 0, 100, 50);
iv.backgroundColor = [UIColor redColor];
iv.layer.cornerRadius = 10.0f;
iv.image = [UIImage imageNamed:@"settings-120.png"];
iv.layer.cornerRadius = 10.0f;
iv.layer.shadowColor = [UIColor blackColor].CGColor;
iv.layer.shadowOffset = CGSizeZero;
iv.layer.shadowRadius = 3.0f;
iv.layer.shadowOpacity = 1.0f;
iv.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:iv.bounds cornerRadius:iv.layer.cornerRadius].CGPath;
[self.view addSubview:iv];

If you want to set an image with UIViewContentModeScaleAspectFill (and not have it overspill), then nest it inside a holder, set the shadow on the holder and clip the imageView:

UIView * holder = [UIView new];
holder.frame = CGRectMake(0, 0, 100, 50);
holder.layer.cornerRadius = 10.0f;
holder.layer.shadowColor = [UIColor whiteColor].CGColor;
holder.layer.shadowOffset = CGSizeZero;
holder.layer.shadowRadius = 3.0f;
holder.layer.shadowOpacity = 1.0f;
holder.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:holder.bounds cornerRadius:holder.layer.cornerRadius].CGPath;
[self.view addSubview:holder];

UIImageView * iv = [UIImageView new];
iv.frame = holder.bounds;
iv.layer.cornerRadius = holder.layer.cornerRadius;
iv.image = [UIImage imageNamed:@"settings-120.png"];
iv.contentMode = UIViewContentModeScaleAspectFill;
iv.clipsToBounds = true;
[holder addSubview:iv];
Johnny Rockex
  • 4,136
  • 3
  • 35
  • 55