gpt4 book ai didi

ios - 将 cornerRadius 和 setbackgroundimage 设置为 UIButton

转载 作者:IT王子 更新时间:2023-10-29 07:37:51 25 4
gpt4 key购买 nike

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

如果我这样做:

button.layer.cornerRadius = 5;

效果很好,如果我这样做的话:

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

角不是圆的。

我知道我可以解决这个问题

 [button.layer setMasksToBounds:YES];

但我专门寻找不同的解决方案,因为我向按钮添加了一些箭头,如果我将掩码设置为边界,箭头将被屏蔽。

编辑:

radialGradient 是用 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;
}

最佳答案

下面是我如何通过代码创建一个按钮并设置它的背景颜色。

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];

下面是与上述代码相关的按钮的图像 enter image description here

您始终可以使用代码来创建背景和边框所需的颜色。希望这对您有所帮助。

关于ios - 将 cornerRadius 和 setbackgroundimage 设置为 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17401032/

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