iOS - 使UIImage与UIButton的大小相同

时间:2016-04-06 06:20:51

标签: ios objective-c uibutton uiimage

我使用

创建一个自定义栏按钮
+ (UIBarButtonItem *)barBtnItem:(id)target action:(SEL)action imageName:(NSString *)imageName frame:(CGRect)frame
{
    UIButton *btn =  [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:frame];
    UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return barBtn;
}

框架大小

CGRectMake(0, 0, 22, 22)

但是,我认为由于宽高比,我的图像会变小但在UIButton中正确居中

但是,我希望图像与UIButton的尺寸相同。

我能这样做吗?

我使用了XCode 7并尝试了它的切片功能。但我无法使它发挥作用。

如果我可以通过代码完成?

我也看过UIEdgeinsets,但我并不完全理解cap / insets概念。

3 个答案:

答案 0 :(得分:1)

将按钮的内容模式设置为UIViewContentModeScaleToFill

btn.imageView.contentMode = UIViewContentModeScaleToFill
btn.imageView.frame = btn.bounds

答案 1 :(得分:1)

在写下面代码后检查:

btn.contentMode= UIViewContentModeScaleToFill;
btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);

仍然无法正常工作,请尝试以下代码行。设置UIButton的背景图片而不是图片。

+ (UIBarButtonItem *)barBtnItem:(id)target action:(SEL)action imageName:(NSString *)imageName frame:(CGRect)frame
{

UIButton *btn =  [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[btn setFrame:frame];
UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
return barBtn;
}

如果不能使用下面的代码行:

 UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:imageName] style:UIBarButtonItemStylePlain target:self action:@selector(handleBack:)];

答案 2 :(得分:0)

你可以通过AutoLayouts来做到这一点! set image从顶部,底部,左侧,右侧等于Button的约束!!