如何根据按钮框架正确计算cornerRadius

Ole*_*huk 5 uibutton ios swift swift3

如何cornerRadius根据按钮的框架计算属性以创建圆角。

我不喜欢cornerRadius为每个按钮项重新定义每个时间角。

我为UIButton.

extension UIButton {

    func setRoundedCorners(){
        self.layer.cornerRadius = 10
        self.layer.borderWidth = 1
    }

}
Run Code Online (Sandbox Code Playgroud)

而且我想知道cornerRadius每次使用此函数时如何动态计算。

主要问题是找到为不同按钮大小计算 .cornerRadius 的函数。下面的示例将显示出很小的差异。

例子:

角半径为 10:

在此处输入图片说明

圆角半径为 15:

在此处输入图片说明

是否可以找到可以计算给出角半径的适当值的函数?

ale*_*wis 6

UIView此扩展可能会帮助您——它根据给定实例的属性计算并设置角半径frame

extension UIView {
    /**
     Magically computes and sets an ideal corner radius.
     */
    public func magicallySetCornerRadius() {
        layer.cornerRadius = 0.188 * min(frame.width, frame.height)
        layer.masksToBounds = true
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我如何在“ViewController.swift”文件中使用它来处理三个不同大小的UIButtons

import UIKit

class ViewController: UIViewController {

    private func addButton(frame: CGRect, backgroundColor: UIColor) {
        let button = UIButton(frame: frame)
        button.backgroundColor = backgroundColor
        button.magicallySetCornerRadius()
        button.layer.borderColor = UIColor.black.cgColor
        button.layer.borderWidth = 1.0
        view.addSubview(button)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        addButton(frame: CGRect(x: 40.0, y: 100.0, width: 100.0, height: 300.0), backgroundColor: .blue)
        addButton(frame: CGRect(x: 160.0, y: 180.0, width: 100.0, height: 100.0), backgroundColor: .green)
        addButton(frame: CGRect(x: 160.0, y: 300.0, width: 180.0, height: 100.0), backgroundColor: .red)
        addButton(frame: CGRect(x: 40.0, y: 420.0, width: 300.0, height: 150.0), backgroundColor: .yellow)
    }

}
Run Code Online (Sandbox Code Playgroud)

...结果如下:

在此输入图像描述


ped*_*uan 1

获得灵活功能的主要思想是根据不同按钮的框架计算适当的角半径

我认为这取决于您作为参数传递的内容:

extension UIButton {
    func setRoundedCorners(ratio: Double?) {
        if let r = ratio {
            self.layer.cornerRadius = self.frame.size.width*r // for specific corner ratio                            
        } else {

            // circle
            // i would put a condition, as width and height differ:
            if(self.frame.size.width == self.frame.size.height) {
                self.layer.cornerRadius = self.frame.size.width/2 // for circles
            } else {
                //
            }
        }
        self.layer.borderWidth = 1
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

let button = UIButton()
button.setRoundedCorners(ratio: 0.25) // shape with rounded corners
button.setRoundedCorners() // circle
Run Code Online (Sandbox Code Playgroud)

  • 如果有人自动投票否决人们的答案,有人愿意回答这个问题吗? (2认同)