繁体   English   中英

如何以编程方式在uiview上拟合图像

[英]How to fit an image on a uiview programmatically

我以编程方式在视图控制器上添加了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];

更改代码如下

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

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

imageView.contentMode = UIViewContentModeScaleAspectFit;

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

我猜你的self.contentView.bounds菜单图像2.JPG的纵横比不同。 为了进行实验,请尝试查看菜单图片2.JPG的分辨率。 例如,如果它是300x150,则其宽高比是(300/150 = 2:1) 将self.contentView.bounds设置为此宽高比,然后绘制图像并检查结果。 它不会伸展。

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

yourImage .contentMode = UIViewContentModeScaleAspectFit;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM