2017-04-15 41 views
2

我以编程方式在视图控制器上添加了uiview作为子视图(称为contentView)。我还以编程方式在该uiview上添加了一个图像。每次我在iPad上运行应用程序时,图像都被拉长了!如何修复图像,使其适合iPad屏幕,但不会拉伸图像?我知道drawInRect是拉伸形象。那么我该如何解决这个问题?如何以编程方式使用uiview上的图像

这是我的代码:

UIGraphicsBeginImageContextWithOptions(self.contentView.bounds.size, self.contentView.opaque, 0.0); 

[[UIImage imageNamed:@"menu image 2.JPG"] drawInRect:self.contentView.bounds]; 

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

[self.contentView addSubview:imageView]; 
+2

没有任何理由对这种复杂的图像assignement? '[[UIImageView alloc] initWithImage:[UIImage imageNamed:@“menu image 2.JPG”]];' - 这应该是所有需要的。为此创建新的图像上下文似乎是一种矫枉过正。 – Losiowaty

回答

2

更改代码如下

UIImage *image = [UIImage imageNamed:@"menu image 2.JPG"]; 

UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

imageView.contentMode = UIViewContentModeScaleAspectFit; 

[self.contentView addSubview:imageView]; 
2

的UIImageView有一个名为contentMode属性,它确定该图像布局如何在视图上下文处理。 contentMode类型为UIViewContentMode

默认值为UIViewContentModeScaleToFill,它在不考虑宽高比的情况下拉伸图像。我认为这是导致问题的变化的纵横比。

如果要缩放图像,但保持纵横比,你有两个选择:

  1. UIViewContentModeScaleAspectFit:这将显示缩放来填充视图图像,但不能夹任何内容(如果纵横比与视图大小不匹配,则会显示水平或垂直波段)

  2. UIViewContentModeScaleAspectFill:这将缩放图像以完全填充视图,没有任何波段 - 这会导致内容被剪裁,如果图像比例与视野比例不匹配。

要设置在Objective-C图像视图的contentMode,请使用以下语法:

UIImage *image = [UIImage imageNamed:@"menu image 2.JPG"]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
imageView.contentMode = UIViewContentModeScaleAspectFill; 
... 

你不应该需要使用自定义的背景绘制该上班了(感谢Losiowaty问我这件事情)。

+1

如果OP已经通过在自定义上下文中绘制图像来创建图像的拉伸版本,这项工作是否会完成? – Losiowaty

+1

好点,忘了提。我会想象OP可以取代自定义上下文绘图。我将更新我的文章以反映图像如何实例化。 +1 – Yasir

+0

我明白。但是,两者都行不通。“Aspect fit”显示垂直频段,“Aspect Fill”则像您所说的那样剪辑内容。我认为最好的解决方案应该是NSLayout约束 - 以编程方式完成尾随,引导,顶部和底部布局约束。任何想法如何以编程方式做到这一点?我是Objective-C的新手。所以我很感激帮助。 – TheProgrammer96

0

我想你的self.contentView.bounds没有与你的菜单图像2.JPG相同的长宽比。对于实验,请尝试查看菜单图像2.JPG的分辨率。例如,如果它是300x150,则它的长宽比是(300/150 = 2:1)。将self.contentView.bounds设置为此宽高比并绘制图像并检查结果。它不会伸展。

-1

请添加这一行代码在您的项目

yourImage .contentMode = UIViewContentModeScaleAspectFit;