gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:31:51 25 4
gpt4 key购买 nike

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

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

我为 UIButton 创建扩展。

extension UIButton {

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

}

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

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

例子:

圆角半径为 10:

: enter image description here

圆角半径为 15:

enter image description here

是否有可能找到函数来计算给出圆角半径的正确值?

最佳答案

这个扩展可能会帮助你——它根据它的 frame 属性为给定的 UIView 实例计算和设置角半径:

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
}
}

下面是我如何在“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)
}

}

...结果是这样的:

enter image description here

关于ios - 如何根据按钮框架正确计算 cornerRadius,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39893383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com