How to set image in circle in swift
import UIKitclass ViewController: UIViewController { @IBOutlet weak var image: UIImageView! override func viewDidLoad() { super.viewDidLoad() image.layer.borderWidth = 1 image.layer.masksToBounds = false image.layer.borderColor = UIColor.black.cgColor image.layer.cornerRadius = image.frame.height/2 image.clipsToBounds = true}
If you want it on an extension
import UIKitextension UIImageView { func makeRounded() { self.layer.borderWidth = 1 self.layer.masksToBounds = false self.layer.borderColor = UIColor.black.cgColor self.layer.cornerRadius = self.frame.height / 2 self.clipsToBounds = true }}
That is all you need....
You can simple create extension:
import UIKitextension UIImageView { func setRounded() { let radius = CGRectGetWidth(self.frame) / 2 self.layer.cornerRadius = radius self.layer.masksToBounds = true }}
and use it as below:
imageView.setRounded()
Based in the answer of @DanielQ
Swift 4 and Swift 3
import UIKitextension UIImageView { func setRounded() { self.layer.cornerRadius = (self.frame.width / 2) //instead of let radius = CGRectGetWidth(self.frame) / 2 self.layer.masksToBounds = true }}
You can use it in any ViewController
with:
imageView.setRounded()