jazzedge
11/28/2017 - 2:03 PM

Swift - Extension to create a round Image with shadow on a UIView

If you have an image which needs to be clippedToBounds, then you can't draw a shadow around it Instead you have to first drop a UIView on your storyboard to act as the background. You add a UIImageView to the UIView you just dropped. Make sure it is constrained to 0,0,0,0 against the underlying background UIView. You set clippedToBounds = true for your imageView, and = false for your background UIView. Then, you set the corner radius of both views to half of their width: let width:CGFloat = imageViewBG.bounds.width imageViewBG.layer.cornerRadius = width/2 imageViewFG.layer.cornerRadius = width/2 Then add your shadow elements to the background view

See: https://stackoverflow.com/questions/39624675/add-shadow-on-uiview-using-swift-3

Source:ViewShadow

Here is the extension with two functions of the same name, one with, the other without parameters.

import UIKit

extension UIView {
    
    // OUTPUT 1
    func dropShadow(scale: Bool = true) {
        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowOffset = CGSize(width: 2, height: 2)
        self.layer.shadowRadius = 1
        
//        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
    
    // OUTPUT 2
    func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
        self.layer.masksToBounds = false
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOpacity = opacity
        self.layer.shadowOffset = offSet
        self.layer.shadowRadius = radius
        
//        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
}


You call if from your view controller file like this:

  @IBOutlet weak var imageViewBG: UIView!
    @IBOutlet weak var imageViewFG: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let width:CGFloat = imageViewBG.bounds.width
        imageViewBG.layer.cornerRadius = width/2
        imageViewFG.layer.cornerRadius = width/2
        
        //imageViewBG.dropShadow()
        imageViewBG.dropShadow(color: UIColor.red, opacity: 0.5, offSet: CGSize(width: 6, height: 6), radius: 5, scale: true)
        
    }