如何使用图像作为按钮背景?

时间:2012-10-18 16:05:55

标签: uiview uibutton uiimage

我有以下图像代表我的按钮:

enter image description here

我想使用该图像创建一个按钮,将其用作背景,但比我提供的图像宽得多。

以下是我尝试的两种方法:

  UIButton *emailSupportButton = [[UIButton alloc] initWithFrame:CGRectMake(25, 315, 200, 60)];
  [emailSupportButton setTitle:@"Email Support" forState:UIControlStateNormal];
  [emailSupportButton setImage:[UIImage imageNamed:@"toolbar-button"] forState:UIControlStateNormal];

此方法导致按钮图像未被拉伸并准确显示.png将如何正常显示。

我尝试的另一种方法是设置背景图像,就像这样......

  UIButton *emailSupportButton = [[UIButton alloc] initWithFrame:CGRectMake(25, 315, 200, 60)];
  [emailSupportButton setTitle:@"Email Support" forState:UIControlStateNormal];
  [emailSupportButton setBackgroundImage:[UIImage imageNamed:@"toolbar-button"] forState:UIControlStateNormal];

这种方法以非常丑陋的方式拉伸图像而不是达到预期的效果,导致按钮几乎是椭圆形的,边框非常难看。

问题是我没有使用正确的方法创建自定义按钮,或者我的图像不适合我想要完成的任务?我的图像是否应该是矩形而不包括按钮的边框,让UIButton为我处理边框/舍入?我的图像是否已经是按钮的大小(这似乎有点限制)?

1 个答案:

答案 0 :(得分:1)

您列出的第二种方法(代码方式)就是您想要的。你缺少的是可伸缩的图像。试试这个:

UIButton *emailSupportButton = [[UIButton alloc] initWithFrame:CGRectMake(25, 315, 200, 60)];
[emailSupportButton setTitle:@"Email Support" forState:UIControlStateNormal];
UIImage *backgroundImage = [UIImage imageNamed:@"toolbar-button"];
CGSize size = backgroundImage.size;
backgroundImage = [backgroundImage stretchableImageWithLeftCapWidth:size.width/2.0 topCapWidth:size.height/2.0];
[emailSupportButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];

如果您只在iOS 5及更高版本上进行部署,那么您将需要使用新的-[UIImage resizableImageWithCapInsets:(UIEdgeInsets)capInsets]; iOS 6还添加-[UIImage resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode];