如何在UIButton中拉伸图像

时间:2012-07-05 14:42:04

标签: ios cocoa uibutton

我正在尝试以编程方式创建自定义UITableViewCell,此单元格的一个子视图将成为一个带有图像的按钮(放大镜的简单图像)。但是,我希望按钮的图像居中并按比例缩小以适应按钮,而不是拉伸以填充整个按钮。下面是我的代码,其中self指的是我将按钮放入的自定义UITableViewCell。

self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.myButton setBackgroundImage:[UIImage imageNamed: @image_name_here"] forState:UIControlStateNormal];
self.myButton.frame = CGRectMake(...//something, something)
self.myButton.imageView.contentMode = UIViewContentModeCenter;
[self.contentView addSubview:self.mySearchHelpButton];

现在,图像会拉伸以填充整个按钮,而不是按比例缩放,以使其非常适合。

我也尝试将contentMode设置为UIViewContentModeScaleAspectFill但这似乎没有改变任何东西。事实上,没有一个不同的内容模式似乎改变了任何东西。

7 个答案:

答案 0 :(得分:64)

您是否尝试过setImage而不是setBackgroundImage

答案 1 :(得分:45)

确保该按钮是自定义UIButton

仅使用setImage:在iOS9上对我不起作用。

但它与myButton.imageView.contentMode = UIViewContentMode.ScaleAspectFit;

结合使用

答案 2 :(得分:36)

在斯威夫特......

button.imageView?.contentMode = .aspectFit

答案 3 :(得分:27)

故事板

属性图片。

您必须在身份检查器 - imageView.contentMode运行时属性中定义特定属性,其中您将值设置为相对于枚举的rawValue位置{ {1}}。 1表示 scaleAspectFit

Set button.imageView.contentMode in Storyboard

按钮的对齐方式,在属性检查器

Full alignment of button

答案 4 :(得分:8)

Swift 4.2

myButton.imageView!.contentMode = .scaleAspectFit

Swift早期版本

myButton.imageView!.contentMode = UIViewContentMode.scaleAspectFit

答案 5 :(得分:0)

我认为你们都没有发现明显的问题。该图像对于按钮而言太大,然后iOS必须猜测您要如何缩放它。确保图像尺寸正确,并且不会出现此问题。当然,这是用于静态图像和您知道其大小的按钮,而不是动态内容。

答案 6 :(得分:0)

快速4.X和5.X

button.imageView!.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
相关问题