2012-07-30 87 views
5

我有同样的问题,因为这里的链接: Can't add a corner radius and a shadow添加圆角到的UIImageView和显示阴影效果

如果我把maskToBounds = YES,我得到的圆角,但没有影子 如果我把maskToBounds = NO ,我得到了影子,但没有圆角。

然后我按照上面那个链接中的说明,设置maskToBounds = NO,“而是设置圆角半径,并用圆角矩形设置阴影的贝塞尔路径,保持二者的半径相同。但是,我没有找到圆角,也没有得到任何影子! (即没有阴影的方形图像)你能帮我解决这个问题吗?我不知道我做错了什么。提前致谢。

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]; 

回答

18

不幸的是,我不认为UIImageView同时支持圆角和阴影。

但是,您可以在UIImageView的超级视图中制作阴影。

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]; 
+0

我认为你的方法会奏效,我会尽快尝试。感谢你的回答。我发布这个问题已经很长时间了,我很高兴看到一个答案。 – John 2012-10-19 19:06:04

+0

什么是'aRect'? – 2013-12-14 00:13:05

+0

aRect是您希望您的imageView所在的位置(即没有容器时的imageView框架)。 – 2014-01-04 02:22:59