Creating a shadow for a UIImageView that has rounded corners?

前端 未结 5 1412
伪装坚强ぢ
伪装坚强ぢ 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:05

    2019

    Finally here is how to

    Properly have an image view, with rounded corners AND shadows.

    It's this simple:

    class ShadowRoundedImageView: UIView {
        @IBInspectable var image: UIImage? = nil {
            didSet {
                imageLayer.contents = image?.cgImage
                shadowLayer.shadowPath = (image == nil) ? nil : shapeAsPath }}
        
        var imageLayer: CALayer = CALayer()
        var shadowLayer: CALayer = CALayer()
        
        var shape: UIBezierPath {
            return UIBezierPath(roundedRect: bounds, cornerRadius:50) }
        
        var shapeAsPath: CGPath {
            return shape.cgPath }
    
        var shapeAsMask: CAShapeLayer {
            let s = CAShapeLayer()
            s.path = shapeAsPath
            return s }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            clipsToBounds = false
            backgroundColor = .clear
            
            self.layer.addSublayer(shadowLayer)
            self.layer.addSublayer(imageLayer) // (in that order)
            
            imageLayer.frame = bounds
            imageLayer.contentsGravity = .resizeAspectFill // (as preferred)
            
            imageLayer.mask = shapeAsMask
            shadowLayer.shadowPath = (image == nil) ? nil : shapeAsPath
            shadowLayer.shadowOpacity = 0.80 // etc ...
        }
    }
    

    Here is the

    Explanation

    1. UIImageView is useless, you use a UIView

    2. You need two layers, one for the shadow and one for the image

    3. To round an image layer you use a mask

    4. To round a shadow layer you use a path

    For the shadow qualities, obviously add code as you see fit

        shadowLayer.shadowOffset = CGSize(width: 0, height: 20)
        shadowLayer.shadowColor = UIColor.purple.cgColor
        shadowLayer.shadowRadius = 5
        shadowLayer.shadowOpacity = 0.80
    

    For the actual shape (the bez path) make it any shape you wish.

    (For example this tip https://stackoverflow.com/a/41553784/294884 shows how to make only one or two corners rounded.)

    Summary

    • Use two layers on a UIView

    Make your bezier and ...

    • Use a mask on the image layer

    • Use a path on the shadow layer

提交回复
热议问题