Circular Image Becoming a Diamond Not Circle - Swift 3

后端 未结 3 1375
天涯浪人
天涯浪人 2021-01-21 06:10

I have been trying to create a circular image but for some reason it has been outputting as a diamond. This is my code:

override func viewDidLoad() {
    display         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 06:21

    The issue is that viewWillLayoutSubviews is too early in the layout process. You can do it in viewDidLayoutSubviews.

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        profilePic.layer.cornerRadius = min(profilePic.frame.width, profilePic.frame.height) / 2
        profilePic.clipsToBounds = true
    }
    

    Or, alternatively, you can use a designable view, and let the view take care of it:

    @IBDesignable class RoundedImageView: UIImageView {
        override func layoutSubviews() {
            super.layoutSubviews()
            layer.cornerRadius = min(bounds.width, bounds.height) / 2
        }
    }
    

    And by making it designable, you can see it rendered with rounded corners right in Interface Builder.

提交回复
热议问题