如何以编程方式在 uiview 上调整图像



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

这是我的代码:

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];

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向我询问此问题)。

更改代码

如下
UIImage *image = [UIImage imageNamed:@"menu image 2.JPG"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.contentView addSubview:imageView];

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

请在您的项目中添加此单行代码

yourImage .contentMode = UIViewContentModeScaleAspectFit;