How to set imageView in circle like imageContacts in Swift correctly?
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)
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))
This is solution which I have used in my app:
var image: UIImage = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.layer.cornerRadius = image.frame.size.width/2
imageView.clipsToBounds = true
Swift 4.0
let image = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.cornerRadius = image.frame.size.width / 2
imageView.clipsToBounds = true