【问题标题】:Make a UIImageView round, add a border, and a shadow around the border制作一个 UIImageView 圆形,添加边框,并在边框周围添加阴影
【发布时间】:2016-11-18 21:36:10
【问题描述】:

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

我有一个 UIImageView,我正在圆角并为其添加边框。然而,我开始添加一些阴影来给我的 UI 一些深度。我正在为我的个人资料图片添加阴影,以下代码非常适合完美的方形图像,该图像被裁剪成完美的圆形。然而,对于非正方形的矩形图像,阴影被应用到图像本身而不是图像视图,所以我最终在裁剪的矩形图像周围有一个圆形边框,它的边缘周围有一个阴影,没有到达圆形边框。关于如何修改代码以将此阴影应用到边框周围而不是 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];

【问题讨论】:

  • 你能提供一张你不喜欢的行为的截图吗?
  • 我其实刚刚完成了fixed的实现,很糟糕,没有commit,所以不能轻易回滚。但基本上,如果我有一个比高宽的图像,阴影只会出现在图像的顶部,被圆圈剪掉,而不是绕着圆圈走。阴影在圆圈内部。如果图片的高度大于宽度,阴影会绕过圆圈的边缘,但会停在图像的边缘。我使用了类似于 Alex 下面的方法。

标签: ios objective-c uiimageview shadow


【解决方案1】:

问题是当你设置cornerRadius时,阴影和其他内容一起被屏蔽了。

您可以在内部使用带有阴影和蒙版 imageView 的中间容器视图。这是代码,但您也可以对 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];

输出:

【讨论】:

  • 我将其标记为正确,因为它基本上是我使用的实现,尽管我确实使用情节提要来初始化视图,并且仅以编程方式进行阴影/角/边框。不过,除了 SB 而不是程序初始化之外,这是我使用的解决方案。
  • 如您所说,阴影应用于内容。对于完美的正方形图像,内容被边框剪裁,并且应用于内容的阴影正确地绕过边框的边缘。将阴影应用到具有相同设置角的父视图就可以了。
  • 这里需要注意的是,如果内容没有被完全遮蔽,那么阴影将不会正确地绕过边缘。即使内容是完美的正方形。这篇博文还展示了“容器”方法:iOS - How to mask and shadow an image
猜你喜欢
  • 2014-07-28
  • 2013-07-13
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2013-01-22
  • 2015-04-26
  • 1970-01-01
  • 2022-11-23
相关资源
最近更新 更多