如何围绕环的中心点绘制圆形按钮?

Luk*_*ton -1 uibutton ios uibezierpath swift

我正在尝试在这样的环中绘制圆形按钮。

在此输入图像描述

我有 6 个 UI 按钮,它们的圆角半径都是 360 度,我试图在 Swift 中做的是将它们均匀地绘制在中心按钮/点周围,就像上图一样。每个圆与其相邻圆的间距相等。实现此功能的最佳方法是什么?我应该创建一条贝塞尔曲线,然后使用数学来绘制该曲线周围的按钮,还是您会建议其他方法?

附带说明的是,我并不是在寻找任何类型的径向菜单,不需要动画。我只是想按照上面的格式绘制现有的 UI 按钮。

谢谢!

vac*_*ama 7

我建议使用数学(三角学)来计算距中心按钮的水平和垂直偏移,然后使用布局锚点来定位按钮。

这是一个独立的示例:

class ViewController: UIViewController {

    func createButton(size: CGFloat) -> UIButton {
        let button = UIButton(type: .custom)
        button.backgroundColor = .red
        button.translatesAutoresizingMaskIntoConstraints = false
        button.widthAnchor.constraint(equalToConstant: size).isActive = true
        button.heightAnchor.constraint(equalToConstant: size).isActive = true
        button.layer.cornerRadius = size / 2

        return button
    }

    func setUpButtons(count: Int, around center: UIView, radius: CGFloat) {
        // compute angular separation of each button
        let degrees = 360 / CGFloat(count)

        for i in 0 ..< count {
            let button = createButton(size: 50)
            self.view.addSubview(button)

            // use trig to compute offsets from center button
            let hOffset = radius * cos(CGFloat(i) * degrees * .pi / 180)
            let vOffset = radius * sin(CGFloat(i) * degrees * .pi / 180)

            // set new button's center relative to the center button's
            // center using centerX and centerY anchors and offsets
            button.centerXAnchor.constraint(equalTo: center.centerXAnchor, constant: hOffset).isActive = true
            button.centerYAnchor.constraint(equalTo: center.centerYAnchor, constant: vOffset).isActive = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let centerButton = createButton(size: 50)
        self.view.addSubview(centerButton)

        // use anchors to place center button in the center of the screen
        centerButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        centerButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

        setUpButtons(count: 6, around: centerButton, radius: 100)
    }

}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 如果不需要中心按钮,只需设置周围的按钮即可self.view

    setupButtons(count: 6, around: self.view, radius: 100)
    
    Run Code Online (Sandbox Code Playgroud)

    或围绕任意点:

    let point = CGPoint(x: 180, y: 300)
    let centerView = UIView(frame: CGRect(origin: point, size: CGSize.zero))
    self.view.addSubview(centerView)
    setUpButtons(count: 6, around: centerView, radius: 140)
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用 aUIView作为中心而不是点更灵活,因为您可以动态移动它UIView,按钮也会随之移动。

这是在模拟器中运行的:

在模拟器中运行演示

  • 半径参数控制中心和环之间的间距。 (2认同)