Is there an easy way to achieve this in Android? Yes, today there is, and it is very simple. Just use the MaterialButton in the Material Components library with the app:cornerRadius attribute. It is enough to obtain a Button with rounded corners.
Rounded corners HTML Buttons You can make rounded corners button by adding border-radius of 5px to 10px on HTML buttons.
Short Answer: YES
You can absolutely make a simple rounded button without the need of an additional background image or writing any code for the same. Just follow the screenshot given below, to set the runtime attributes for the button, to get the desired result.
It won't show in the Storyboard
but it will work fine when you run the project.
Note:
The 'Key Path' layer.cornerRadius
and value is 5. The value needs to be changed according to the height and width of the button. The formula for it is the height of button * 0.50. So play around the value to see the expected rounded button in the simulator or on the physical device. This procedure will look tedious when you have more than one button to be rounded in the storyboard.
You can do something like this:
@IBDesignable class MyButton: UIButton
{
override func layoutSubviews() {
super.layoutSubviews()
updateCornerRadius()
}
@IBInspectable var rounded: Bool = false {
didSet {
updateCornerRadius()
}
}
func updateCornerRadius() {
layer.cornerRadius = rounded ? frame.size.height / 2 : 0
}
}
Set class to MyButton
in Identity Inspector
and in IB you will have rounded
property:
To do it in the storyboard, you need to use an image for the button.
Alternatively you can do it in code:
btn.layer.cornerRadius = 10
btn.clipsToBounds = true
Insert the code in RoundButton class.
import UIKit
@IBDesignable
class RoundButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 0{
didSet{
self.layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderWidth: CGFloat = 0{
didSet{
self.layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor = UIColor.clear{
didSet{
self.layer.borderColor = borderColor.cgColor
}
}
}
Refer the image.
I found the easiest way to do this, is by setting the cornerRadius to half of the height of the view.
button.layer.cornerRadius = button.bounds.size.height/2
You can connect IBOutlet
of yur button from storyboard.
Then you can set corner radius
of your button to make it's corner round.
for example, your outlet
is myButton
then,
Obj - C
self.myButton.layer.cornerRadius = 5.0 ;
Swift
myButton.layer.cornerRadius = 5.0
If you want exact round button then your button's width
and height
must be equal
and cornerRadius
must be equal to height or width / 2 (half of the width or height).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With