ios - 如何向圆形 UIImageView 或 UIView 添加阴影?

标签 ios uiview uiimageview calayer shadow

我正在尝试制作一个圆圈 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;

最佳答案

使用 CALayershadowPath property并添加带有圆角矩形的 UIBezierPath

self.pic.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.pic.frame cornerRadius:50.0].CGPath;

编辑

对于正方形 ImageView ,此技术不能直接起作用,因为正如您所说, ImageView 会变回正方形。原因:您设置了 clipsToBounds = NO 来显示移除角半径剪裁的阴影,其中 imageViewcontainer 的 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;

生成的效果如截图所示,

enter image description here

关于ios - 如何向圆形 UIImageView 或 UIView 添加阴影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18403578/

相关文章:

iphone - 如何让 UITextView 在触摸其 UIView subview 后成为FirstResponder?

ios - 在 ios 中拉伸(stretch)图像

ios - UITableView 中的圆形 UIImageView 没有性能影响?

ios - 在 ios 中为动画 uiimageview 添加 mask

ios - AFNetworking SSL 证书失败 iOS

ios - FMDatabase增量真空

ios - 为无尽的跑酷游戏创建动态大小的 SKSpriteNode 平台

ios - 具有自定义初始化的自定义 UIView 不起作用

ios - 检查日期是否存在于 objective-c 中的这一年

ios - 停止 UIView 中的所有异步任务