UIView的contentMode属性总结

x33g5p2x  于2021-11-18 转载在 其他  
字(2.3k)|赞(0)|评价(0)|浏览(296)

UIView的contentMode属性

最初知道这个属性还是以前面试的时候,面试官看到我app的一个图片有些变形,于是考了我这个问题。确实之前没有仔细思考过,一堆枚举值看上去也挺头疼,这次把它总结一下。

我们知道,定义的UIView的frame大小,和它实际需要显示的内容的大小并不总是一直的。这个问题在使用UIImageView的时候格外容易发生。很有可能图片的真实大小、长宽比例和定义的frame不一样。那么这时候系统会如何处理这个图片呢,答案就在于UIView的contentMode属性。

UIViewContentMode

UIViewContentMode是一个枚举类型,作为UIView的contentMode属性的值。一共有一下这些可选值(Swift中去掉前面的“UIViewContentMode”前缀)

  • UIViewContentModeScaleToFill,
  • UIViewContentModeScaleAspectFit,
  • UIViewContentModeScaleAspectFill,
  • UIViewContentModeRedraw,
  • UIViewContentModeCenter,
  • UIViewContentModeTop,
  • UIViewContentModeBottom,
  • UIViewContentModeLeft,
  • UIViewContentModeRight,
  • UIViewContentModeTopLeft,
  • UIViewContentModeTopRight,
  • UIViewContentModeBottomLeft,
  • UIViewContentModeBottomRight,

观察命名发现,前三个值有一个Scale。而比较让人迷糊的也正是这三个值的区别。后面的这些值,根据名字都非常容易理解对应意思。以UIViewContentModeLeft为例,就是图片左对齐显示,能显示多少就显示多少。

UIViewContentModeScale

Scale在英文中有比例,缩放的意思。Scale up和Scale down是分别有放大和缩小的意思。所以前三个以UIViewContentModeScale开头的属性,表示图片会被进行缩放。所以对应的,其他没有Scale的属性,都是指图片会保持原来的大小。

Aspect和Fill

接下来注意到,以UIViewContentModeScale为前缀的三个值,有两个有“Aspect”,还有两个有“Fill”。fit和fill比较好理解,前者表示适应大小,而后者表示完全填满。aspect这个单词有角度的意思,不过我搞不明白它在这里的意思。所以还是看一下苹果官方对这三个值的解释:

* UIViewContentModeScaleToFill

From Apple: The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary.

From Xamarin: Scales the contents to fit the new bounds, this might distort the contents.

中文翻译: 这个选项通过缩放其中内容(往往是图片)的大小来符合View自己的大小,如果需要的话会改变内容的长宽比例

简单来说就是:扭曲、填满

* UIViewContentModeScaleAspectFit

From Apple: The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.

From Xamarin: Scales the contents so that everything is visible, while preserving the aspect ratio. Any areas that are not filled become transparent. (In the image, the UIImage.BackgroundColor was set to black to emphasize the scaling behavior.)

中文翻译: 这个选项通过按比例缩放内容(往往是图片)的大小来符合View的大小,与此同时,保持内容的长宽比例不变。而整个View没有被覆盖到的地方都是透明的(也就说会显示View的backgroundColor)。

简单来说就是:不变形、尽可能填满、留空

* UIViewContentModeScaleAspectFill

From Apple: The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.

From Xamarin: Scales the contents to fill the new bounaries of the view, while preserving the aspect ratio. This means that the contents might be clipped.

中文翻译: 这个选项通过按比例缩放内容(往往是图片)的大小来填充整个View,与此同时,保持内容的长宽比例不变。 因此,内容的某些部分可能会被剪裁掉。

简单来说就是:不变形、完全填满

示例

最后放一张其他博客里看到的图片,结合图片解释这三者的异同:

相关文章