我正在尝试制作一个圆圈 UIImageView
,它可以工作。以下是我用来制作它的方法:
[self.pic.layer setMasksToBounds:YES];
[self.pic.layer setCornerRadius:50.0];
我想给 UIImageView
添加一些阴影。下面的代码确实为我的 ImageView 添加了一些阴影,但是, ImageView 变回了正方形。有人可以给我一些解决这个问题的建议吗?下面是我用来添加阴影的代码:
self.pic.layer.shadowColor = [UIColor purpleColor].CGColor;
self.pic.layer.shadowOffset = CGSizeMake(0, 1);
self.pic.layer.shadowOpacity = 1;
self.pic.layer.shadowRadius = 1.0;
self.pic.clipsToBounds = NO;
最佳答案
使用 CALayer
的 shadowPath
property并添加带有圆角矩形的 UIBezierPath
self.pic.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.pic.frame cornerRadius:50.0].CGPath;
编辑
对于正方形 ImageView ,此技术不能直接起作用,因为正如您所说, ImageView 会变回正方形。原因:您设置了 clipsToBounds = NO
来显示移除角半径剪裁的阴影,其中 imageView
是 container
的 subview 。
解决方法:
在容器 View 中添加 ImageView ,然后将图层阴影应用于此容器。以下是我试过的代码。
[self.imageView.layer setCornerRadius:60.0];
[self.imageView.layer setMasksToBounds:YES];
self.imageView.clipsToBounds = YES;
self.container.backgroundColor = [UIColor clearColor];
self.container.layer.shadowColor = [UIColor blackColor].CGColor;
self.container.layer.shadowOffset = CGSizeMake(5,15);
self.container.layer.shadowOpacity = 0.5;
self.container.layer.shadowRadius = 2.0;
self.container.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.container.bounds cornerRadius:100.0].CGPath;
生成的效果如截图所示,
关于ios - 如何向圆形 UIImageView 或 UIView 添加阴影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18403578/