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:
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! :)
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
}
}
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
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP