本文介绍了为具有圆角的 UIImageView 创建阴影?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有圆角和阴影的 ImageView 以赋予它一些深度.我能够为 UIImageView 创建阴影,但是每当我添加代码以使其具有圆角时,它只有圆角而没有阴影.我有一个名为 myImageIBOutlet,它位于 viewDidLoad 函数内.有人对如何使其工作有任何想法吗?我做错了什么?

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,并应用了阴影属性.如果您还希望阴影被四舍五入,请使用带有 roundedRectcornerRadiusUIBezierPath 构造函数.

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 创建阴影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 02:21