如何更改UIBarButtonItem图像大小

时间:2012-05-23 08:16:58

标签: iphone objective-c ios uibarbuttonitem uinavigationitem

使用UIBarbuttonItem,initWithImage我得到一张我想要更小的图片。

我觉得绝对没有办法调整图像大小。

UIedgeInsetMake根本不运行。调整图片的大小也不起作用(像素化)。 我有一个@ 2x 48x48图标和一个普通的24x24。创建一个空白边框较大的新图片无效。

如果我使用20x20,它会像素化。无论如何。

任何解决方案?谢谢!

3 个答案:

答案 0 :(得分:6)

这可以通过以下方式实现,

  1. UIBarbuttonItem的开放大小检查器
  2. 更改“条形项”的值 - >图像插图 - >顶/底/左/右。
  3. 试一试......

答案 1 :(得分:3)

您可以使用自定义BarbuttonItem设置图像,并使用下面的方法调整标题大小:

+(UIBarButtonItem *)createToolBarButtonItemWithTitle:(NSString *)t target:(id)tgt action:(SEL)a
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
// Since the buttons can be any width we use a thin image with a stretchable center point
UIImage *buttonImage = [[UIImage imageNamed:@"toolbarbutton_button_mouseup.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];
UIImage *buttonPressedImage = [[UIImage imageNamed:@"toolbarbutton_button_mouseover.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];
[[button titleLabel] setFont:[UIFont boldSystemFontOfSize:12.0f]];
//[[button titleLabel] setFont:[UIFont fontWithName:@"Futura-Medium" size:12.0]];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[[button titleLabel] setShadowOffset:CGSizeMake(0.0, 1.0)];

CGRect buttonFrame = [button frame];
buttonFrame.size.width = [t sizeWithFont:[UIFont boldSystemFontOfSize:12.0]].width + 24.0;

//Applicable only for iPhone FrameFun
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && [[[NSUserDefaults standardUserDefaults] stringForKey:@"is_Landscape"] isEqualToString:@"landscape"]) {
    buttonFrame.size.height = 23.0;
}else {

    buttonFrame.size.height = buttonImage.size.height;
}

[button setFrame:buttonFrame];

[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:buttonPressedImage forState:UIControlStateHighlighted];

[button setTitle:t forState:UIControlStateNormal];

[button addTarget:tgt action:a forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
return [buttonItem autorelease];

}

此方法可让您使用所需图像制作按钮的动态大小。 在这里,我使用stretchableImageWithLeftCapWidth来调整图像。我认为它会对你有所帮助。您也可以使用整个方法来制作Custom BarButton。

答案 2 :(得分:1)

如果要更改按钮的大小以匹配图像,最好创建UIButton并使UIBarButtonItem自定义。在UIBarButtonItem中,initWithImage缩放图像以适合UIBarButtonItem。

观看this anser,了解有关如何执行此操作的详细信息。

相关问题