带有圆角的UIButton,使用方形setBackgroundImage

Ric*_*ick 5 iphone ios

所以我创建了一个按钮.我希望它有圆角而没有制作圆形.png文件我可以设置背景图像.我可以绕过角落.但是,当我设置背景图像时,圆角会消失.

我很久以前就这样做了一次,但似乎无法让它恢复正常.如何才能做到这一点?

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 addTarget:self action:@selector(goSpecials)
  forControlEvents:UIControlEventTouchUpInside];
[button1 setTitle:@"Specials" forState:UIControlStateNormal];
button1.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:(15.0)];
[button1 setTitleColor:[self colorWithHexString:buttonColor] forState:UIControlStateNormal];
button1.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: @"button.png"]]; 
 //[button1 setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
button1.frame = CGRectMake(20.0, 232.0, 135.0, 32.0);
button1.layer.borderColor = [UIColor blackColor].CGColor;
button1.layer.borderWidth = 0.5f;
button1.layer.cornerRadius = 8.0f;
[self.view addSubview:button1];
Run Code Online (Sandbox Code Playgroud)

button.png: 在此输入图像描述

小智 18

将maskToBounds属性添加到按钮.

button1.layer.masksToBounds = YES;
Run Code Online (Sandbox Code Playgroud)