ios - 制作一个 UIImageView 圆形,添加边框,并在边框周围添加阴影

标签 ios objective-c uiimageview shadow

我知道那里有类似的问题,但还没有找到可以帮助我解决问题的答案。如果您看过一个,请随时将其标记为重复,但请确保它回答了整个问题,而不仅仅是相似的部分。

我有一个 UIImageView,我正在圆角并为其添加边框。但是,我开始添加一些阴影来给我的 UI 一些深度。我正在为我的个人资料图片添加阴影,下面的代码非常适合完美的方形图像,它被裁剪成完美的圆形。然而,对于非正方形矩形图像,阴影应用于图像本身而不是 ImageView ,所以我最终在裁剪后的矩形图像周围有一个圆形边框,它的边缘周围有一个阴影,没有到达圆形边框。关于如何修改我的代码以将此阴影应用于边框而不是 UIImageView 中的图像的任何见解?

谢谢

//Set profile image view to be rounded (default appears rounded due to alpha background, need rest to appear rounded as well
[self.profileImageView layoutIfNeeded];
CALayer *imageLayer = self.profileImageView.layer;
[imageLayer setCornerRadius:self.profileImageView.frame.size.width/2];
[imageLayer setBorderWidth:1];
[imageLayer setBorderColor:[[UIColor colorWithRed:78.0/255.0 green:82.0/255.0 blue:85.0/255.0 alpha:1] CGColor] ];
[imageLayer setMasksToBounds:YES];

//Apply shadows to necessary views for the job badge
[self.profileImageView.layer setShadowColor:[[UIColor blackColor] CGColor]];
[self.profileImageView.layer setShadowRadius:4.0f];
[self.profileImageView.layer setShadowOffset:CGSizeMake(0, -3)];
[self.profileImageView.layer setShadowOpacity:0.5f];

最佳答案

问题是当您设置 cornerRadius 时,阴影会与其他内容一起被屏蔽。

您可以使用内部包含阴影和蒙版 imageView 的中间容器 View 。这是代码,但您也可以使用 Interface Builder 和自动布局执行相同的操作:

UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
[containerView.layer setShadowColor:[[UIColor blackColor] CGColor]];
[containerView.layer setShadowRadius:4.0f];
[containerView.layer setShadowOffset:CGSizeMake(0, -3)];
[containerView.layer setShadowOpacity:0.5f];
[self.view addSubview:containerView];

UIImageView *imageView = [[UIImageView alloc] initWithFrame:containerView.bounds];
imageView.image = [UIImage imageNamed:@"rgb"];
[imageView.layer setCornerRadius:imageView.frame.size.width/2];
[imageView.layer setBorderWidth:1];
[imageView.layer setBorderColor:[[UIColor colorWithRed:78.0/255.0 green:82.0/255.0 blue:85.0/255.0 alpha:1] CGColor] ];
[imageView.layer setMasksToBounds:YES];
[containerView addSubview:imageView];

输出:

enter image description here

关于ios - 制作一个 UIImageView 圆形,添加边框,并在边框周围添加阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686296/

相关文章:

objective-c - iPad 纵向和横向模式的尺寸调整类

ios - swift 2.0 - "Argument passed to call that takes no arguments"

ios - iOS drawInRect内存泄漏-ARC

iphone - Objective C ivars 或 @property

iphone - 如何访问显示发布到墙上的应用程序名称的链接?

Swift - ImageView 动画

iphone - 使用 CGAffineTransform 倾斜 UIImageView

iphone - 有时 UIImageView 似乎拒绝使用 iPhone 相机拍摄的图像

ios - 为什么CALayer的类别可以声明一个属性而不需要实现并直接使用它?

ios - 如何在 startWithGraphPath Facebook iOS 中标记好友