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

前端 未结 6 2050
迷失自我
迷失自我 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:45

    Without a container but with a background view here is my 2 cents

    As a swift 2.2 extension

        image?.applyCircleShadow(5, shadowOpacity: 1)
    
    extension UIView {
        func applyCircleShadow(shadowRadius: CGFloat = 2,
                               shadowOpacity: Float = 0.3,
                               shadowColor: CGColor = UIColor.blackColor().CGColor,
                               shadowOffset: CGSize = CGSize.zero) {
            layer.cornerRadius = frame.size.height / 2
            layer.masksToBounds = false
            layer.shadowColor = shadowColor
            layer.shadowOffset = shadowOffset
            layer.shadowRadius = shadowRadius
            layer.shadowOpacity = shadowOpacity
        }
    }
    extension UIImageView {
        override func applyCircleShadow(shadowRadius: CGFloat = 2,
                                        shadowOpacity: Float = 0.3,
                                        shadowColor: CGColor = UIColor.blackColor().CGColor,
                                        shadowOffset: CGSize = CGSize.zero) {
    
            // Use UIImageView.hashvalue as background view tag (should be unique)
            let background: UIView = superview?.viewWithTag(hashValue) ?? UIView()
            background.frame = frame
            background.backgroundColor = backgroundColor
            background.tag = hashValue
            background.applyCircleShadow(shadowRadius, shadowOpacity: shadowOpacity, shadowColor: shadowColor, shadowOffset: shadowOffset)
            layer.cornerRadius = background.layer.cornerRadius
            layer.masksToBounds = true
            superview?.insertSubview(background, belowSubview: self)
        }
    }
    

提交回复
热议问题