按比例制作UIImageView及其UIImage比例,无需额外填充

时间:2012-10-15 15:33:40

标签: ios uiimageview rotation uiimage

我有一个包含UIImageView的UIView。 UIImageViews的工作方式类似于应用程序的品牌标识。当我旋转设备时,包含UIView的大小会自动调整以对应屏幕的横向或纵向比例。

我想要实现的是让UIImageView相应缩放,同时保持左边距比例。

这是顶部白色“横幅”的实际代码:

UIView *topBanner = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, height_topBanner)];
[topBanner setAutoresizingMask:(UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin)];
[topBanner setBackgroundColor:[UIColor whiteColor]];
topBanner.autoresizesSubviews = YES;

    // the logo
    UIImage *topBanner_logo = [UIImage imageNamed:@"logo.png"];
    float logoAspectRatio = topBanner_logo.size.width/topBanner_logo.size.height;
    topBanner_logoView = [[UIImageView alloc] initWithFrame:CGRectMake(topBanner.frame.size.width/100*3, topBanner.frame.size.height/100*7, (topBanner.frame.size.height/100*86)*logoAspectRatio, topBanner.frame.size.height/100*86)];
    [topBanner_logoView setImage:topBanner_logo];
    topBanner_logoView.backgroundColor = [UIColor blueColor];
    topBanner_logoView.contentMode = UIViewContentModeScaleAspectFit;
    [topBanner_logoView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin)];
    [topBanner addSubview:topBanner_logoView];

[self.view addSubview:topBanner];

这是我的出发点:启动时的肖像iPad:

Startup in portrait mode

当我在横向中旋转它时会发生这种情况: Landscape mode after the startup

正如你所看到的,UIImage的比例还可以,但是我得到了额外的边框(我设置了UIImageView的背景颜色以突出它),因为UIImageView会自行延伸以跟随其大小的变化容器,UIImage适合UIImageView并放在它的中心。

当我以横向模式直接启动应用程序时,会发生相同的反转: Startup in landscape mode

然后我旋转它:

portrait mode after startup

...我在顶部和底部都有额外的边框。

我确实看到我可以编写一个函数来重新计算每个旋转变化的每个大小,但我问自己是否有办法设置UIImageView和UIImage使其工作而不会破坏自动旋转/调整大小iOS的程序。听起来很简单!

3 个答案:

答案 0 :(得分:0)

您已将自动调整大小蒙版设置为灵活的高度和宽度:

[topBanner_logoView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin)];

如果你不这样做,默认情况是视图不会有机会大小,因此图像也不会。

答案 1 :(得分:0)

我认为这是因为topBanner_logoView.contentMode = UIViewContentModeScaleAspectFit;

尝试topBanner_logoView.contentMode = UIViewContentModeCentertopBanner_logoView.contentMode = UIViewContentModeLeft以防止UIImageView的图片调整大小(并获得填充)。

如果UIImageView正在调整大小,请删除自动调整遮罩。

答案 2 :(得分:0)

您可以通过不使用UIViewContentModeScaleAspectFit来解决此问题,而是计算图像的纵横比,并使用它来明确地根据另一个(宽度或高度)显示宽度或高度。

e.g。我旋转到横向,所以我希望高度为视图的80%。

    CGFloat w = logo.image.size.width;
    CGFloat h = logo.image.size.height;
    CGFloat a = w / h;

    CGFloat h_use = self.view.height *0.8;
    CGFloat w_use = h_use*a;

此外,将内容模式设置为UIViewContentModeScaleAspectFill,而不是您已明确设置宽高比。

相关问题