Set cornerRadius и setbackgroundimage для UIButton
Я пытаюсь установить cornerRadius UIButton, но я не знаю, как это сделать.
Если мне это нравится:
button.layer.cornerRadius = 5;
работает хорошо, если мне это нравится:
button.layer.cornerRadius = 5;
[button setBackgroundColor:[UIColor colorWithPatternImage:radialGradient]];
углы не закруглены.
Я знаю, что смогу решить эту проблему.
[button.layer setMasksToBounds:YES];
но я специально ищу другое решение, потому что я добавляю несколько стрелок к кнопке, и если я устанавливаю маску на границы, стрелка маскируется.
ИЗМЕНИТЬ:
радиальныйГрадиент сделан 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 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;
}
Ответы
Ответ 1
Вот как я мог бы создать кнопку с помощью кода и установить его цвет фона.
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]()
Вы всегда можете играть с кодом и создавать цвета, которые вам нужны для фона и границы. Надеюсь, это поможет вам.
Ответ 2
btn.clipsToBounds = YES;
Я просто добавил это, и это сработало для меня. Я действительно мог установить радиус угла UIButton с настройкой изображения на этот конкретный UIButton.
Ответ 3
Вы также можете:
btn.clipsToBounds = true;
Ответ 4
//создаем такую кнопку
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];
До этого добавьте QuartzCore Framework и импортируйте QuartzCore/CoreAnimation.h в свой .h файл.
надеюсь, что это поможет вам.
Ответ 5
Использование 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()
}
Добавлено как расширение для 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()
}
}
}
Этот подход также позволит вам добавить тень на кнопку в отличие от использования clipsToBounds
.
Ответ 6
Если вы используете изображение на фоне кнопки, вам нужно установить для clipsTobounds
значение true.
button.layer.cornerRadius = 10
button.clipsToBounds = true
Ответ 7
Установите угловой радиус в инспекторе для кнопки. См. Фото
![enter image description here]()
Установите фоновое изображение в инспекторе атрибутов для кнопки. Смотрите фото
![enter image description here]()