How to set imageView in circle like imageContacts in Swift correctly? How to set imageView in circle like imageContacts in Swift correctly? swift swift

How to set imageView in circle like imageContacts in Swift correctly?


This is solution which I have used in my app:

var image: UIImage = UIImage(named: "imageName")imageView.layer.borderWidth = 1.0imageView.layer.masksToBounds = falseimageView.layer.borderColor = UIColor.whiteColor().CGColorimageView.layer.cornerRadius = image.frame.size.width/2imageView.clipsToBounds = true

Swift 4.0

let image = UIImage(named: "imageName")imageView.layer.borderWidth = 1.0imageView.layer.masksToBounds = falseimageView.layer.borderColor = UIColor.white.cgColorimageView.layer.cornerRadius = image.frame.size.width / 2imageView.clipsToBounds = true


What frame size are you using for image? I can get a perfect circle if I set the frame to be a square.

let image = UIImageView(frame: CGRectMake(0, 0, 100, 100))


Fast and Simple solution.

How to mask UIImage to Circle without cropping with Swift.

extension UIImageView {  public func maskCircle(anyImage: UIImage) {    self.contentMode = UIViewContentMode.ScaleAspectFill    self.layer.cornerRadius = self.frame.height / 2    self.layer.masksToBounds = false    self.clipsToBounds = true   // make square(* must to make circle),    // resize(reduce the kilobyte) and    // fix rotation.   self.image = anyImage  }}

How to call:

let anyAvatarImage:UIImage = UIImage(named: "avatar")!avatarImageView.maskCircle(anyAvatarImage)