【发布时间】:2010-04-25 11:10:59
【问题描述】:
我希望以编程方式创建一个自定义 UIButton(不是子类),我希望它有一个随着 UIButton 宽度的增加而拉伸的背景图像。我该怎么做?
【问题讨论】:
标签: cocoa-touch uikit uibutton
我希望以编程方式创建一个自定义 UIButton(不是子类),我希望它有一个随着 UIButton 宽度的增加而拉伸的背景图像。我该怎么做?
【问题讨论】:
标签: cocoa-touch uikit uibutton
首先创建一个可拉伸的UIImage(假设按钮图像末尾的“cap”为10px):
UIImage *backgroundImage = [[UIImage imageNamed:@"ImageBackground.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
然后使用可拉伸的图片作为背景:
[myButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];
当您在 UIButton 上为 UIControlStateNormal 设置 backgroundImage 时,它将充当 所有 状态的背景,除非您为任何其他状态显式设置不同的 backgroundImage。 p>
【讨论】:
NSLog)您的backgroundImage 不为零。如果+[UIImage imageNamed:] 找不到你的图片,它会返回 nil。
-stretchableImage… 接受 2 个整数作为输入,而不是浮点数。
background: 0。
UIImage 找不到您的图像。确保具有该 exact 名称(区分大小写)的图像在您的 Xcode 项目中,而不仅仅是在 Xcode 项目的文件夹中。要将图像添加到项目中,请将其从 Finder 拖到项目窗口中。
更好的是,使用 UIView 的 contentStretch 属性。否则,如果您使用 stretchableImageWithLeftCapWidth 来缩小图形或拉伸具有光照或光泽效果的复杂图形,您可能会得到一些令人讨厌的惊喜。
【讨论】:
好吧,UIView 的 contentStretch 属性将是正确的解决方案,但不幸的是它不适用于 UIButton 背景属性(至少 XCode 4.0.2)。它甚至在 IB 中公开,因此您不需要任何代码。
【讨论】:
您必须将使用“stretchableImageWithLeftCapWidth:topCapHeight:”方法创建的 UIImage 设置为按钮背景。例如:
UIImage *yourBackgroundImage = [[UIImage imageNamed:@"yourImage.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
yourButton.backgroundColor = [UIColor colorWithPatternImage:yourBackgroundImage];
【讨论】: