I am trying to create a circular image and I have implemeted the right code but I do not know why it does not get rounded below is my code
lazy var profileImage: UIImageView = {
let image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
image.layer.borderColor = UIColor.blue.cgColor
image.layer.borderWidth = 1.5
image.image = UIImage(named: "prof.jpg")
image.contentMode = .scaleAspectFit
image.layer.cornerRadius = image.frame.size.width / 2
image.clipsToBounds = true
return image
}()
and my constraints are
fileprivate func layout() {
view.addSubview(profileImage)
NSLayoutConstraint.activate([
profileImage.centerXAnchor.constraint(equalTo: view.centerXAnchor),
profileImage.centerYAnchor.constraint(equalTo: view.centerYAnchor),
profileImage.heightAnchor.constraint(equalToConstant: 200),
profileImage.widthAnchor.constraint(equalToConstant: 200),
])
}
layout() is then added to viewDidLoad
You’re not giving your UIImageView a frame when it’s initialised so it uses
.zero
as a default. This means that when you accessimage.frame.size.width
you are getting a value of 0.What I would suggest is to move your
image.layer.cornerRadius = image.frame.size.width / 2
into theviewDidLayoutSubviews
override on yourUIViewController
class.You could also create a custom class that subclasses
UIImageView
and implements the same logic. Theoverride
forUIImageView
would belayoutSubviews
.Image doesn't have a frame
*image.layer.cornerRadius = image.frame.size.width / 2*
inside the closure.So set the corner radius after the profileImage is set with its constraints