简体   繁体   English

缩放任何图像以适合UIImageView

[英]Scaling any image to fit UIImageView

I'm a little but confused as to how I could make an image taken by an iPhone camera to fit into a UIImageView of any given size. 我有点困惑,但是如何让iPhone相机拍摄的图像适合任何给定尺寸的UIImageView。 Obviously the scale would be different for each imageview so the image wouldn't "fit" perfectly. 显然,每个图像视图的比例会有所不同,因此图像不会完全“适合”。 But let's say I have a UIImageView of size 200pt x 400 pt. 但是,假设我有一个尺寸为200pt x 400 pt的UIImageView。 What would be the best way to fit a UIImage to this UIImageView ? UIImage到这个UIImageView的最佳方法是什么?

I think I want to do something like the following: 我想我想做类似以下的事情:

[imageView setContentMode:UIViewContentModeScaleAspectFill];

This sort of works, but it seems to increase the size of my UIImageView but I don't want this... 这种工作,但它似乎增加了我的UIImageView的大小,但我不希望这...

在此输入图像描述

Use setContentMode:UIViewContentModeScaleAspectFit (not Fill ; Fill means that one dimension is permitted to be too large for the image view, and you will be able to see the excess spill over if the image view's clipsToBounds is not set). 使用setContentMode:UIViewContentModeScaleAspectFit (不Fill ; Fill意味着允许一个维度对于图像视图来说太大,如果未设置图像视图的clipsToBounds ,您将能够看到多余的溢出)。

Also, note that setting the image of an existing UIImageView when using auto layout can cause the image view's size to change (because the size of the image determines the intrinsic size of the image view). 此外,请注意设置image的现有的UIImageView的当使用自动布局可导致图像视图的大小改变(因为图像的大小确定图像视图的固有尺寸)。 If you don't want that, add constraints to maintain the height and width at some constant value (eg explicit height and width constraints). 如果您不想这样做,请添加约束以将高度和宽度保持在某个常量值(例如显式高度和宽度约束)。

Actually UIViewContentModeScaleAspectFill will also work if you enable clipping as arturdev suggested. 实际上,如果你按照arturdev建议启用剪辑,UIViewContentModeScaleAspectFill也会起作用。 Set clipToBounds to YES (or enable "Clip Subviews" in storyboard). 将clipToBounds设置为YES(或在storyboard中启用“Clip Subviews”)。 This will cause your image to stretch over the entire view, and the excess gets cut out. 这将导致您的图像在整个视图上伸展,并且多余部分被剪切掉。 In some cases this is the preferred behaviour over UIViewContentModeScaleAspectFit; 在某些情况下,这是优于UIViewContentModeScaleAspectFit的行为; the latter will leave empty spaces if the image does not perfectly fit the view rectangle. 如果图像不完全适合视图矩形,后者将留下空白空间。 在此输入图像描述

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

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