iPhone:以原始尺寸显示图像

时间:2011-07-28 09:07:07

标签: iphone uiimageview viewcontroller

我正在尝试将imageview的帧设置为图像的原始大小,并将其显示在视图的中心。我为此编写了以下代码,但图像仍然出现在整个屏幕上!假设图像大小为320x88,它显示调整大小/拉伸到320x460!我希望它出现在屏幕的中心,所以我将Y坐标设置为(460-88)/ 2,但它不起作用。有谁可以帮我解决这个问题。感谢。

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath]];

if(imageView.image.size.width == IPHONE4_RES_WIDTH)
    [imageView setFrame: CGRectMake(0, 0, imageView.image.size.width/2, imageView.image.size.height/2)];

UIViewController *viewController = [[[UIViewController alloc] init] autorelease];
viewController.view.backgroundColor = [UIColor blackColor];

NSLog(@"%f : %f",viewController.view.bounds.size.height, imageView.bounds.size.height);

viewController.view = imageView;
viewController.view.contentMode = UIViewContentModeCenter;

[self.navigationController pushViewController:viewController animated:YES];

4 个答案:

答案 0 :(得分:15)

试试这个

    viewController.view.contentMode=UIViewContentModeCenter;

答案 1 :(得分:2)

您可以将uiimageview设置为不拉伸图像..即使它是完整尺寸,它也会在您设置时在中心显示图像

imageView.contentMode = UIViewContentModeCenter

答案 2 :(得分:2)

尝试在storyboard文件中实现相同时,请回答这个问题。同样作为补充:在同一事物的故事板中,您可以选择Mode = Center的{​​{1}}

enter image description here

答案 3 :(得分:0)

以下完美符合我的要求!

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath]];

// Reduce the width and height for iPhone 4 res
if(imageView.image.size.width == IPHONE4_RES_WIDTH)
    [imageView setFrame: CGRectMake(0, 0, imageView.image.size.width/2, imageView.image.size.height/2)];


UIViewController *viewController = [[[UIViewController alloc] init] autorelease];
viewController.view.backgroundColor = [UIColor blackColor];

float X = (viewController.view.bounds.size.width - imageView.bounds.size.width)/2;
float Y = (viewController.view.bounds.size.height - imageView.bounds.size.height)/2 - 50; // Size of tabbar and navigation bar deducted

NSLog(@"(%f, %f) : (%f,%f)",X,Y,imageView.bounds.size.width,imageView.bounds.size.height);

[viewController.view addSubview:imageView];

//viewController.view = imageView;
//viewController.view.contentMode = UIViewContentModeCenter;

// Set in the center of the screen
if(imageView.image.size.width == IPHONE4_RES_WIDTH)
    [imageView  setFrame: CGRectMake(X, Y, imageView.image.size.width/2, imageView.image.size.height/2)];
else
    [imageView  setFrame: CGRectMake(X, Y, imageView.image.size.width, imageView.image.size.height)];

[self.navigationController pushViewController:viewController animated:YES];