The problem of creating a shadow behind a rounded UIImageView

I have a rounded UIImageView. When I add a shadow to it, I lose the rounded corner. How can I get a shadow with a rounded corner?

//Avatar CGRect rect; rect = CGRectMake(13, 10, 48, 48); avatarImageView = [[TCImageView alloc] initWithURL:[NSURL URLWithString:nil] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; avatarImageView.frame = rect; avatarImageView.caching = YES; //Round the corners CALayer * layer = [avatarImageView layer]; [layer setMasksToBounds:YES]; [layer setCornerRadius:9.0]; //Add a shadow avatarImageView.layer.shadowColor = [UIColor grayColor].CGColor; avatarImageView.layer.shadowOffset = CGSizeMake(0, 1); avatarImageView.layer.shadowOpacity = 1; avatarImageView.layer.shadowRadius = 9.0; avatarImageView.clipsToBounds = NO; [self.contentView addSubview: avatarImageView]; 
+7
source share
1 answer

The function that makes your image appear with a rounded corner is the one that hides the shadow: [layer setMasksToBounds: YES] . What you can do is put your ImageView in a UIView view, which acts like a container providing a shadow.

Thus, the code may look like this (I just typed it, did not compile it, though)

 //Avatar CGRect rect; rect = CGRectMake(13, 10, 48, 48); avatarImageView = [[TCImageView alloc] initWithURL:[NSURL URLWithString:nil] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; avatarImageView.frame = rect; avatarImageView.caching = YES; //Round the corners CALayer * layer = [avatarImageView layer]; [layer setMasksToBounds:YES]; [layer setCornerRadius:9.0]; //Add a shadow by wrapping the avatar into a container UIView * container = [[UIView alloc] initWithFrame: rect]; avatarImageView.frame = CGRectMake(0,0,rect.size.width, rect.size.height); // setup shadow layer and corner container.layer.shadowColor = [UIColor grayColor].CGColor; container.layer.shadowOffset = CGSizeMake(0, 1); container.layer.shadowOpacity = 1; container.layer.shadowRadius = 9.0; container.layer.cornerRadius = 9.0; container.clipsToBounds = NO; // combine the views [container addSubview: avatarImageView]; [self.contentView addSubview: container]; [container release]; 
+17
source

All Articles