ios - 帧改变图像大小

标签 ios xcode image toolbar

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

-(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;

} 

最佳答案

您有几种不同的选择。如果您不是绝对需要使按钮的大小与其背景图像不同,则可以设置背景图像,然后获取不会拉伸(stretch)该背景图像的大小,以分配给按钮的框架,例如:

[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)];

如果您真的想在不失真的情况下更改背景图像的大小(例如,您可能想通过复制背景图像中心的像素来拉长背景图像),您应该查看 resizableImageWithCapInsets: UIImage 提供的方法。

如果出于某种原因你需要 button0 有一个特定的框架并且你希望它的背景是不同的大小,你可以继承 UIButton 并在你的子类中显式实现:

- (CGRect)backgroundRectForBounds:(CGRect)bounds

并为您的背景图像返回一个正确大小的框架,而不管按钮的边界如何。

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

关于ios - 帧改变图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878412/

相关文章:

css - 图像没有出现在 div 中?是因为 CSS 吗?

ios - 将类作为参数传递并使用此类实例化对象

ios - SWRevealController 不适用于 NavigationController

ios - UIApplicationStateActive 时如何处理通知

ios - 如何在 Xcode Interface Builder 中设置约束,以便 View 相应地改变它们的宽度或高度?

ios - 从 Cloudkit 加载空属性时代码崩溃 - 使用 Swift

python - 用python从图像中提取裙子

image - 如何将单 channel IplImage* 转换为位图^

iphone - 使用嵌套的 NSMutableDictionary

ios - Swift UIButton - 如何删除下划线?