Reputation:
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:
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! :)
Upvotes: 1
Views: 332
Reputation: 2644
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
Upvotes: 2
Reputation: 196
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
}
}
profilePicture.willCircle
Storyboard:
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
Upvotes: 0
Reputation: 626
Adjust UIButton's layer:
profilePicture.imageView.contentMode = .scaleAspectFit
let cornerRadius = 25 // 50 * 0.5
profilePicture.layer.cornerRadius = cornerRadius
profilePicture.layer.masksToBounds = true
Upvotes: 3