以编程方式制作圆形按钮

Make a circular button programatically

我想在我的 iOS 应用程序中创建一个通告 UIButton

该按钮用于为用户创建头像。

这是圆形头像:

这是选择图片后的样子:

可以看到按钮太大了,不是圆形的。 这是我的代码:

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
    }
  

选择的图片要刚好填在头像人物头像的圆圈内。我使用的是自动布局,所以我找到的大多数教程都对我没有帮助!

谢谢! :)

调整UIButton的图层:

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

您需要将 UIButton 的角半径更改为它大小的一半

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

以编程方式:

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

故事板:

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