【问题标题】:Scaling down a UIButton's background image when using initWithFrame:使用 initWithFrame 时缩小 UIButton 的背景图像:
【发布时间】:2014-05-23 07:20:30
【问题描述】:

这是我第一次设计 iOS 应用,所以我想确保我正确理解了这种行为。

我为 Photoshop 中的导航栏设计了一个自定义栏按钮图标。我在 Photoshop 中保存的最终图像是 102 x 45,是的,我意识到这些尺寸大于 iOS 7 设计指南中推荐的 44x44。

不管怎样,我把我的图片放到了asset文件夹中,然后用下面的代码编程设置了bar button item:

UIImage* firstButtonImage = [UIImage imageNamed:@"loginbutton1"];

    CGRect frame = CGRectMake(0, 0, 102, 45);

    UIButton * someButton = [[UIButton alloc] initWithFrame:frame];
    [someButton setBackgroundImage:firstButtonImage forState:UIControlStateNormal];
    [someButton addTarget:self action:@selector(didTapLoginButton:)
         forControlEvents:UIControlEventTouchUpInside];

    self.rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:someButton];

    self.navItem.rightBarButtonItem = self.rightBarButton;

如您所见,我将框架的宽度和高度设置为图像的确切大小。当我第一次运行该应用程序时,我不喜欢该图像并认为它太大了。所以我在这个语句中更改了宽度和高度参数:

CGRect frame = CGRectMake(0, 0, 70, 30);

现在图像在 iPhone 屏幕上看起来很完美。这是在 iPhone 4s 上。

所以我的主要问题是,当我更改帧大小时实际发生了什么?由于框架现在小于实际图像大小,图像是否会自动缩小以适合框架内?

【问题讨论】:

  • 希望我的回答能帮到你。

标签: ios uiimageview uibutton uiimage contentmode


【解决方案1】:

是的,因为您使用的是backgroundImage(不是Image),所以图像会被缩放。两张图片有不同的行为。

检查Xcode Interface Builder,你可以在那里看到,你可以设置两个图像:图像和背景。背景是UIImage,它会针对UIButton 的整个帧进行缩放。

UIButton Class Reference 允许您访问imageimageView(不是backgroundImageimageView

因为您可以访问imageView,所以您可以通过以下方式更改图像的模式:

[[someButton imageView] setContentMode:UIViewContentModeBottomLeft];

UIView Class Reference你可以查看苹果提供的所有UIViewContentModes

您可以检查一下您的代码是否有所更改:

[someButton setImage:firstButtonImage forState:UIControlStateNormal];
[[someButton imageView] setContentMode:UIViewContentModeBottomRight];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多