UIView中contentMode属性的基本功能

UIView的属性contentMode用于当视图的bounds(边界)发生变化时来确定视图如何布局,也就是说此属性通常用于实现可调整大小的控件。

UIViewContentMode的常量定义:
typedef NS_ENUM(NSInteger, UIViewContentMode) {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
};
设置UIImageView图片常用的三个类型:
  • UIViewContentModeScaleToFill

通过更改内容的横纵比来实现内容的缩放,以适应自身的大小。UIImageView设置contentMode = ScaleToFill 会使图片充满容器,因为要保持内容适配容器个宽高,所以图片在容器中会被拉伸;

  • UIViewContentModeScaleAspectFit

通过保持纵横比来缩放内容以适应视图大小,视图边界的任何剩余区域都是透明的。保持长宽比的前提下,缩放图片,使得图片在容器内完整显示出来。

  • UIViewContentModeScaleAspectFill

    缩放内容以保证填充视图大小,可以剪裁部分内容以填充视图的边界。在保持长宽比的前提下,缩放图片,使图片充满容器,内容四周可能会被剪切。

效果图:
  1. 原图效果:

    原图
  2. ScaleToFill效果:

    IMG_0047
  3. AspectFit效果:

    AspectFit
  4. AspectFill效果:

AspectFill
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容