Reputation: 60869
I have a rounded UIImageView. When I add a shadow to it, I lose the rounded corner. How can I have 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];
Upvotes: 7
Views: 6259
Reputation: 2531
The feature, which makes your image appear with rounded corner is the one which hides the shadow: [layer setMasksToBounds: YES]
. The thing you can do, put your ImageView within a UIView subview which acts as a container providing the shadow.
So code could look like this (I just typed it down, 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];
Upvotes: 17