2012-01-02 119 views
5

我有一个UIButton没有文本,并有2个图像我想使用(一个用于正常状态,另一个用于选定状态)。图像比按钮尺寸小。为UIButton防止UIImage调整大小

如何确保在绘制按钮时缩放图像?设置imageView属性只能正常更改正常状态的比例,但不能选择正常状态。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 

    [button setImage:imageNormal forState:UIControlStateNormal]; 
    [button setImage:imageSelected forState:UIControlStateSelected]; 

    // this shows the correct scale in normal mode but not when button is tapped 
    button.imageView.contentScaleFactor = 1.0; 
    button.imageView.contentMode = UIViewContentModeCenter; 
+0

**注意!!! **只有背景图像被默认拉伸以匹配框架。使用“图像”,而不是背景图像,如果你想中心 – Fattie 2014-05-12 11:31:47

回答

10

假设你有图像的高度和宽度,你可以这样做:

int topBottom = (button.frame.size.height - imageHeight)/2; 
int leftRight = (button.frame.size.width - imageWidth)/2; 

button.imageEdgeInsets = UIEdgeInsetsMake(topBottom,leftRight,topBottom,leftRight); 

然后你不需要设置contentMode /比例因子。

+0

非常感谢! – james075 2013-03-01 17:38:37