UIImageview not getting rounded

女生的网名这么多〃 提交于 2019-12-24 19:08:24

问题


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


回答1:


You’re not giving your UIImageView a frame when it’s initialised so it uses .zero as a default. This means that when you access image.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 the viewDidLayoutSubviews override on your UIViewController class.

You could also create a custom class that subclasses UIImageView and implements the same logic. The override for UIImageView would be layoutSubviews.




回答2:


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

profileImage.layoutIfNeeded()
profileImage.layer.cornerRadius = profileImage.frame.size.width / 2


来源:https://stackoverflow.com/questions/56415203/uiimageview-not-getting-rounded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!