ios 将 cornerRadius 和 setbackgroundimage 设置为 UIButton

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17401032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:09:54  来源:igfitidea点击:

set cornerRadius and setbackgroundimage to UIButton

iosuibuttoncornerradiussetbackground

提问by

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

我正在尝试设置 UIButton 的cornerRadius,但我不知道该怎么做。

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

RadialGradient 是 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;
}

回答by Adrian P

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.

您可以随时使用代码并创建背景和边框所需的颜色。希望这会帮助你。

回答by Pratik Gujarati

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.

我刚刚添加了这个,它对我有用。我实际上能够通过将图像设置为该特定 UIButton 来将角半径设置为 UIButton。

回答by Angels

You can also have:

您还可以拥有:

btn.clipsToBounds = true;

回答by Alex

//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.

在此之前添加 QuartzCore 框架并在 .h 文件中导入 QuartzCore/CoreAnimation.h。

hope it will helps you..

希望它会帮助你..

回答by HafizAnser

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

如果您在按钮背景中使用图像,则需要设置clipsTobounds为 true。

button.layer.cornerRadius = 10 
button.clipsToBounds = true

回答by Joony

Using UIGraphicsImageRenderer, you can use the cgContextproperty of UIGraphicsImageRendererContextto access the CGContextand add a rounded path:

使用UIGraphicsImageRenderer,您可以使用 的cgContext属性UIGraphicsImageRendererContext访问CGContext并添加圆角路径:

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:

作为扩展添加到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.

与使用clipsToBounds.

回答by Manish Mahajan

Set corner Radius in Identity Inspector for Button. See Pic

在 Identity Inspector 中为按钮设置角半径。见图片

enter image description here

在此处输入图片说明

Set Background image in Attribute Inspector for Button. See pic

在属性检查器中为按钮设置背景图像。看图

enter image description here

在此处输入图片说明