TransWikia.com

Make a circular button programatically

Stack Overflow Asked by user14469311 on December 19, 2020

I want to create a circular UIButton in my iOS application.

The button is for creating a profile picture for the user.

This is the circular profile picture:

And this is how it looks like after a picture was chosen:
enter image description here

You can see that the button is too big and not circular.
This is my code:

func setUpProfilePicture() {
        profileIcon = UIImage(named: "characteer")!
        profilePicture.setImage(profileIcon, for: .normal)
        profilePicture.contentMode = .scaleAspectFill
        profilePicture.addTarget(self, action: #selector(handleSelectedPhoto), for: .touchUpInside)
        
        self.view.addSubview(profilePicture)
        
        profilePicture.translatesAutoresizingMaskIntoConstraints = false
        profilePicture.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        profilePicture.topAnchor.constraint(equalTo: view.topAnchor, constant: -180).isActive = true
        profilePicture.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 50).isActive = true
        profilePicture.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 50).isActive = true
    }
  

The chosen picture should be just filled in the circle of the profile picture character image. I worked with auto layouts, so the most tutorials I found didn’t help me!

Thank you! :)

3 Answers

Adjust UIButton's layer:

profilePicture.imageView.contentMode = .scaleAspectFit
let cornerRadius = 25 // 50 * 0.5
profilePicture.layer.cornerRadius = cornerRadius
profilePicture.layer.masksToBounds = true

Correct answer by siarheibrazil on December 19, 2020

Programmatically:

private extension UIView { 
    func willCircle() {
    self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) * 0.5
    self.layer.masksToBounds = true
    self.clipsToBounds = true
    }
}
  • usage: profilePicture.willCircle

Storyboard:

@IBInspectable
var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue
        layer.masksToBounds = newValue > 0
    }
}

Answered by DrainOpener on December 19, 2020

You will need to change the corner radius of your UIButton to be half of it's size

profileIcon.imageView?.contentMode = .scaleAspectFit
profileIcon.layer.cornerRadius = min(profileIcon.frame.height, profileIcon.frame.width) / 2
profileIcon.layer.masksToBounds = true

Answered by אורי orihpt on December 19, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP