Ios 帧改变图像大小

Ios 帧改变图像大小,ios,xcode,image,toolbar,Ios,Xcode,Image,Toolbar,我正试图将“设置”按钮添加到工具栏中,但我必须为其设置的框架正在改变图像尺寸。如何设置帧而不影响图像本身。映像存储在@1x、@2x和@3x的资产目录中 -(void)viewWillAppear:(BOOL)animated{ //Toolbar buttons UIView *buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)]; buttonContainer.backgroundCo

我正试图将“设置”按钮添加到工具栏中,但我必须为其设置的框架正在改变图像尺寸。如何设置帧而不影响图像本身。映像存储在@1x、@2x和@3x的资产目录中

-(void)viewWillAppear:(BOOL)animated{

 //Toolbar buttons
  UIView *buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
  buttonContainer.backgroundColor = [UIColor clearColor];
  UIButton *button0 = [UIButton buttonWithType:UIButtonTypeCustom];
--[button0 setFrame:CGRectMake(0, 0, 44, 44)];-------------
  [button0 setBackgroundImage:[UIImage imageNamed:@"settings-128(1).png"] forState:UIControlStateNormal];
  [button0 addTarget:self action:@selector(button0Action:) forControlEvents:UIControlEventTouchUpInside];
  [button0 setShowsTouchWhenHighlighted:YES];
  [buttonContainer addSubview:button0];

  self.navigationItem.titleView = buttonContainer;

} 

你有几个不同的选择。如果不一定要使按钮的大小与其背景图像的大小不同,则可以设置背景图像,然后获得不会拉伸该背景图像的大小,以指定给按钮的边框,如:

[button0 setBackgroundImage:[UIImage imageNamed:@"settings-128(1).png"] forState:UIControlStateNormal];
const CGSize button0Size = [button0 sizeThatFits:CGSizeZero];
[button0 setFrame:CGRectMake(0, 0, button0Size.width, button0Size.height)];
如果您确实希望在不失真的情况下更改背景图像的大小(例如,您可能希望通过复制背景图像中心的像素来拉长背景图像),则应查看
UIImage
提供的
调整大小的图像带帽插图:
方法

如果出于某种原因,您需要
button0
来拥有一个特定的帧,并且希望其背景大小不同,那么您可以将
UIButton
子类化,并在子类中显式实现:

- (CGRect)backgroundRectForBounds:(CGRect)bounds
并为背景图像返回大小正确的帧,而不考虑按钮的边界

当然,如果所有其他操作都失败,您可以使用清晰的像素填充资源
settings-128(1).png
,使图像大小与所需的帧大小匹配。如果可以避免,我不建议使用这种方法,因为它会导致将来对按钮大小的任何更改需要仔细更改图像(以及图像的2x和3x版本)