Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How properly calculate cornerRadius depending on the button frame

How to calculate cornerRadius property based on frame of the button to create rounded corners.

I do not like to redefine each time corner cornerRadius for each button item.

I create extension for the UIButton.

extension UIButton {

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

}

And i would like to know how too calculate dynamically cornerRadius each time i use this function.

The main issue to find function that will calculate .cornerRadius for different button sizes. Example below will show small difference.

Example:

Corner radius is 10:

:enter image description here

Corner radius is 15:

enter image description here

Is it possible to find function that will calculate proper value that will give corner radius?

like image 404
Oleg Gordiichuk Avatar asked Oct 06 '16 10:10

Oleg Gordiichuk


2 Answers

This extension may help you -- it computes and sets the corner radius for a given UIView instance based on its frame property:

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

Here's how I've used it in a "ViewController.swift" file for three differently sized 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)
    }

}

... and this is what the result looks like:

enter image description here

like image 83
alexjrlewis Avatar answered Sep 19 '22 20:09

alexjrlewis


Try this code:

btn1, btn2 and btnarrival are UIButton instances:

 btn1.setCornerRadius()
 btn2.setCornerRadius()
 btnarrival.setCornerRadius()


extension UIButton {
    func setCornerRadius() {
        layer.cornerRadius = frame.size.height / 2.0
        clipsToBounds = true
    }
}

Did u want button look like this then try this my code..

like image 42
Himanshu Moradiya Avatar answered Sep 23 '22 20:09

Himanshu Moradiya