How can I add shadow to a circle UIImageView or UIView?

前端 未结 6 2041
迷失自我
迷失自我 2020-12-25 13:31

I am trying to make a circle UIImageView, and it works. Below is the way I use to make it:

[self.pic.layer setMasksToBounds:YES];
[self.pic.laye         


        
6条回答
  •  独厮守ぢ
    2020-12-25 13:48

    I created custom classes (swift 3 or 4) and it works very well :

    class RoundShadowImageView: RoundView {
    
        var imageView = RoundImageView()
    
        var image: UIImage!  {
            didSet {
                imageView.image = image
            }
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            addSubview(imageView)
            needsUpdateConstraints()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            addSubview(imageView)
            needsUpdateConstraints()
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            clipsToBounds = false
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOpacity = 0.1
            layer.shadowOffset = CGSize(width: 0, height: 10)
            layer.shadowRadius = 10
            layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: frame.height / 2.0).cgPath
        }
    
        override func updateConstraints() {
            super.updateConstraints()
    
            imageView.snp.makeConstraints { (make) -> Void in
                make.height.width.equalTo(self)
                make.center.equalTo(self)
            }
        }
    }
    
    class RoundImageView: UIImageView {
    
        override func layoutSubviews() {
            super.layoutSubviews()
            let radius: CGFloat = self.bounds.size.height / 2.0
            layer.cornerRadius = radius
            clipsToBounds = true
        }
    }
    
    class RoundView: UIView {
    
        override func layoutSubviews() {
            super.layoutSubviews()
            let radius: CGFloat = self.bounds.size.height / 2.0
            layer.cornerRadius = radius
            clipsToBounds = true
        }
    }
    

    There are 2 classes to make a container and an image view round. And the main class which combines both of them: the one that you'll call.

提交回复
热议问题