50

I am trying to set cornerRadius of UIButton but I dont know how to do it.

If I do like this:

button.layer.cornerRadius = 5;

works well, if I do like this :

button.layer.cornerRadius = 5;
[button setBackgroundColor:[UIColor colorWithPatternImage:radialGradient]];

the corners are not rounded.

I know I could solve this whit

 [button.layer setMasksToBounds:YES];

but I specifically looking for different solution, because I add some arrows to the button and if I set mask to bounds the arrow are masked.

EDIT :

radialGradient is made whit func

+ (UIImage *)getRadialGradientImage:(CGSize)size centre:(CGPoint)centre radius:(float)radius startColor:(UIColor *)startColor endColor:(UIColor *)endColor{

// Initialise
UIGraphicsBeginImageContextWithOptions(size, YES, 1);

// Create the gradient's colours
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };

const CGFloat *component_first = CGColorGetComponents([startColor CGColor]);

CGFloat red1 = component_first[0];
CGFloat green1 = component_first[1];
CGFloat blue1 = component_first[2];

const CGFloat *component_second = CGColorGetComponents([endColor CGColor]);
CGFloat red2 = component_second[0];
CGFloat green2 = component_second[1];
CGFloat blue2 = component_second[2];

const CGFloat components[8] = { red1,green1,blue1,1,red2,green2,blue2,1}; // End color

CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef myGradient = CGGradientCreateWithColorComponents (myColorspace, components, locations, num_locations);

// Normalise the 0-1 ranged inputs to the width of the image
CGPoint myCentrePoint = CGPointMake(centre.x * size.width, centre.y * size.height);
float myRadius = MIN(size.width, size.height) * radius;

// Draw it!
CGContextDrawRadialGradient (UIGraphicsGetCurrentContext(), myGradient, myCentrePoint,
                             0, myCentrePoint, myRadius,
                             kCGGradientDrawsAfterEndLocation);

// Grab it as an autoreleased image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

// Clean up
CGColorSpaceRelease(myColorspace); // Necessary?
CGGradientRelease(myGradient); // Necessary?
UIGraphicsEndImageContext(); // Clean up
return image;
}

7 Answers7

48

Here is how I would create a button through code and set its background color.

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 100,50);
[btn setTitle:@"Hello" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor colorWithRed:128.0/255.0f green:0.0/255.0f  blue:0.0/255.0f alpha:0.7]];
btn.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);//width and height should be same  value
btn.clipsToBounds = YES;

btn.layer.cornerRadius = 20;//half of the width
btn.layer.borderColor=[UIColor redColor].CGColor;
btn.layer.borderWidth=2.0f;

[self.view addSubview:btn];

Below is the image of the button that is related with the above code enter image description here

You can always play around with code and create the colors that you need for background and border. Hope this would help you out.

Adrian P
  • 6,439
  • 4
  • 36
  • 55
21
btn.clipsToBounds = YES; 

i Just added this and it worked for me. I was actually able to set corner radius to UIButton with setting an image to that particular UIButton.

Pratik Gujarati
  • 282
  • 2
  • 3
6

You can also have:

btn.clipsToBounds = true;
Tunaki
  • 116,530
  • 39
  • 281
  • 370
Angels
  • 79
  • 1
  • 2
  • Be careful, `YES`/`NO` should be used with Objective-C while `true`/`false` may be used for Swift. – JAL Mar 17 '16 at 17:19
  • 1
    @JAL You can also use `true`/`TRUE` and `false`/`FALSE` in Objective-C, along with `YES` and `NO`. – Luke Mar 17 '16 at 21:35
  • It's better to use YES/NO with the Objective-C BOOL type, since true/false map to the C bool type. – JAL Mar 17 '16 at 21:52
6

If you are using the image in your button background then you need to set clipsTobounds to true.

button.layer.cornerRadius = 10 
button.clipsToBounds = true
Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
HafizAnser
  • 448
  • 6
  • 6
3

//create button like this

     UIButton *cancel=[[UIButton alloc]initWithFrame:CGRectMake(9, 9,35,35)];
    cancel.backgroundColor=[UIColor  colorWithPatternImage:[UIImage imageNamed:@"BackX.png"]];
[cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [cancel.layer setBorderColor: [[UIColor blackColor] CGColor]];
    [cancel.layer setBorderWidth: 1.0];
    cancel.contentMode=UIViewContentModeScaleAspectFill;
    cancel.clipsToBounds=YES;
    cancel.layer.cornerRadius=8.0;
    [cancel addTarget:self action:@selector(cancelbtnclk1:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancel];

Before that add QuartzCore Framework and import QuartzCore/CoreAnimation.h in your .h file.

hope it will helps you..

Alex
  • 643
  • 8
  • 13
0

Using UIGraphicsImageRenderer, you can use the cgContext property of UIGraphicsImageRendererContext to access the CGContext and add a rounded path:

UIGraphicsImageRenderer(size: size).image { context in
    let rect = CGRect(origin: .zero, size: size)
    let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
    context.cgContext.addPath(clipPath)
    context.cgContext.setFillColor(self.cgColor)
    context.cgContext.fillPath()
}

Added as an extension to UIColor:

extension UIColor {
    public func image(_ size: CGSize = CGSize(width: 10, height: 10), cornerRadius: CGFloat = 4) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { context in
            let rect = CGRect(origin: .zero, size: size)
            let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
            context.cgContext.addPath(clipPath)
            context.cgContext.setFillColor(self.cgColor)
            context.cgContext.fillPath()
        }
    }
}

This approach will also allow you to add a shadow to the button unlike using clipsToBounds.

Joony
  • 4,170
  • 2
  • 26
  • 37
-1

Set corner Radius in Identity Inspector for Button. See Pic

enter image description here

Set Background image in Attribute Inspector for Button. See pic

enter image description here

Manish Mahajan
  • 1,763
  • 1
  • 9
  • 17