我有一个圆形的UIImageView。当我为它添加阴影时,我会失去圆角。我怎么能有圆角的阴影?
//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];
答案 0 :(得分:17)
使图像显示为圆角的功能是隐藏阴影的功能:[layer setMasksToBounds: YES]
。您可以做的事情,将您的ImageView放在UIView子视图中,该子视图充当提供阴影的容器。
所以代码看起来像这样(我只是输入它,但是没有编译它)
//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];