为具有圆角的UIImageView创建阴影? [英] Creating a shadow for a UIImageView that has rounded corners?
问题描述
我正在尝试创建一个 ImageView
,它有圆角和阴影以给它一些深度。我能够为 UIImageView
创建一个阴影,但每当我添加代码以使其具有圆角时,它只有圆角而没有阴影。我有 IBOutlet
名为 myImage
,它位于 viewDidLoad $ c内$ c>功能。有没有人对如何使其工作有任何想法?我做错了什么?
I am trying to create an ImageView
that has rounded corners and a shadow to give it some depth. I was able to create a shadow for the UIImageView
, but whenever I added the code to also make it have rounded corners, it only had rounded corners with no shadow. I have an IBOutlet
named myImage
, and it is inside of the viewDidLoad
function. Does anybody have any ideas on how to make it work? What am I doing wrong?
override func viewDidLoad() {
super.ViewDidLoad()
myImage.layer.shadowColor = UIColor.black.cgColor
myImage.layer.shadowOpacity = 1
myImage.layer.shadowOffset = CGSize.zero
myImage.layer.shadowRadius = 10
myImage.layer.shadowPath = UIBezierPath(rect: myImage.bounds).cgPath
myImage.layer.shouldRasterize = false
myImage.layer.cornerRadius = 10
myImage.clipsToBounds = true
}
推荐答案
如果设置 clipsToBounds
到 true
,这会绕过角落,但会阻止阴影出现。要解决此问题,您可以创建两个视图。容器视图应该有阴影,其子视图应该有圆角。
If you set clipsToBounds
to true
, this will round the corners but prevent the shadow from appearing. In order to resolve this, you can create two views. The container view should have the shadow, and its subview should have the rounded corners.
容器视图有 clipsToBounds
设置为 false
,并应用了阴影属性。如果你想要阴影也被舍入,使用 UIBezierPath
构造函数,它接受 roundedRect
和 cornerRadius
。
The container view has clipsToBounds
set to false
, and has the shadow properties applied. If you want the shadow to be rounded as well, use the UIBezierPath
constructor that takes in a roundedRect
and cornerRadius
.
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
outerView.clipsToBounds = false
outerView.layer.shadowColor = UIColor.black.cgColor
outerView.layer.shadowOpacity = 1
outerView.layer.shadowOffset = CGSize.zero
outerView.layer.shadowRadius = 10
outerView.layer.shadowPath = UIBezierPath(roundedRect: outerView.bounds, cornerRadius: 10).cgPath
接下来,设置图像视图(或任何其他类型的 UIView
)与容器视图的大小相同,将 clipsToBounds
设置为 true
,并给它一个 cornerRadius
。
Next, set the image view (or any other type of UIView
) to be the same size of the container view, set clipsToBounds
to true
, and give it a cornerRadius
.
let myImage = UIImageView(frame: outerView.bounds)
myImage.clipsToBounds = true
myImage.layer.cornerRadius = 10
最后,记得让图片视图成为容器视图的子视图。
Finally, remember to make the image view a subview of the container view.
outerView.addSubview(myImage)
结果应如下所示:
这篇关于为具有圆角的UIImageView创建阴影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!