UIImageview not getting rounded

2019-08-17 14:29发布

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

2条回答
三岁会撩人
2楼-- · 2019-08-17 14:46

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-08-17 14:47

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
查看更多
登录 后发表回答