Creating a shadow for a UIImageView that has rounded corners?

前端 未结 5 1405
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 14:17

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,

5条回答
  •  春和景丽
    2020-11-27 15:10

    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.

    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
    

    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)
    

    The result should look something like this:

提交回复
热议问题