简体   繁体   English

如何使用圆角向 UIView 添加内阴影

[英]How to add inner shadow to UIView with rounded corners

I have to add an inner shadow to a UIView that has rounded corners.我必须为具有圆角的UIView添加内阴影。

I saw several answers on SO that add inner shadows to UIViews but they don't work as I want to, because they add the shadow to the whole rectangle, not accounting for the rounded corners.我在 SO 上看到了几个答案,它们向 UIViews 添加了内部阴影,但它们不能按我的意愿工作,因为它们将阴影添加到整个矩形,而不是考虑圆角。

See this image as an example of what I would like to achieve:将此图像视为我想要实现的示例:

在此处输入图像描述

It's a trick.这是一个把戏。 You give shadow and border to same view, the shadow will fall inside the view.您将阴影和边框赋予同一视图,阴影将落在视图内。 please make sure the background color of view is clear.请确保视图的背景颜色清晰。 use the below code for reference.使用下面的代码作为参考。

yourView.layer.shadowColor = UIColor.gray.cgColor
yourView.layer.shadowOpacity = 0.3
yourView.layer.shadowOffset = CGSize.zero
yourView.layer.shadowRadius = 6
yourView.layer.masksToBounds = true
yourView.layer.borderWidth = 1.5
yourView.layer.borderColor = UIColor.white.cgColor
yourView.layer.cornerRadius = imageView.bounds.width / 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM