添加UIImageView并处理大小/适合度

时间:2013-03-27 21:24:59

标签: ios ios5 uiview uiimageview uiimage

我按如下方式创建视图:

// Create sub view for Logo
logoView =[[UIView alloc] initWithFrame:CGRectMake(0,0,screen.size.width,(screen.size.height - 230))];
[logoView setBackgroundColor:[UIColor blueColor]];
UIImageView *bgLogoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg-welcomeLogoView.png"]];
[logoView addSubview:bgLogoView];
//NSLog(@"the button view height is %f",(screen.size.height - 230));
logoView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

我有一个logoView的设置框。高度为230(iphone4<)和318(iphone5)。我为这个块创建了一个640x460px的图像。

如何使此图像适合视图。此刻它将全尺寸图像加载到块中,实际上是该尺寸的一半......图像的尺寸是质量的两倍。我在运行ios5的iphone4上进行测试。

我确信有一两行错过了以某种方式使图像适合周围视图的视图边界。

3 个答案:

答案 0 :(得分:3)

您需要重置图像视图的框架。如你所知,图像视图的框架将是图像的大小。另外,设置图像视图的contentMode。最后,设置图像视图的autoresizingMask

logoView =[[UIView alloc] initWithFrame:CGRectMake(0,0,screen.size.width,(screen.size.height - 230))];
[logoView setBackgroundColor:[UIColor blueColor]];
UIImageView *bgLogoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg-welcomeLogoView.png"]];
bgLogoView.frame = logoView.bounds; // reset the frame
bgLogoView.contentMode = UIViewContentModeScaleAspectFit; // or other desired mode
bgLogoView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[logoView addSubview:bgLogoView];
//NSLog(@"the button view height is %f",(screen.size.height - 230));
logoView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

答案 1 :(得分:2)

这样的东西
bgLogoView.contentMode = UIViewContentModeScaleAspectFit;

查看UIView的contentMode属性。可能的值是:

typedef enum {
   UIViewContentModeScaleToFill,
   UIViewContentModeScaleAspectFit,
   UIViewContentModeScaleAspectFill,
   UIViewContentModeRedraw,
   UIViewContentModeCenter,
   UIViewContentModeTop,
   UIViewContentModeBottom,
   UIViewContentModeLeft,
   UIViewContentModeRight,
   UIViewContentModeTopLeft,
   UIViewContentModeTopRight,
   UIViewContentModeBottomLeft,
   UIViewContentModeBottomRight,
} UIViewContentMode;

答案 2 :(得分:0)

试试这个:

UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 230)];
NSString *bgFilePath = [[NSBundle mainBundle] pathForResource:@"bg-welcomeLogoView"
                                                       ofType:@"png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:bgFilePath];
[bgImageView setImage:img];
[logoView addSubview:bgImageView];

您可以在initWithFrame中更改UIImageView的大小: