浅谈UIView的contentMode属性

Content Modes###

每一个view都有一个contentMode属性。这个属性用来控制view如何重用界面的内容以响应界面的几何变化,或者是将整个内容完全重用。
当一个view第一次被展示的时候,它会将自己的内容渲染为一张位图。之后,改变view的几何尺寸不会总是导致这个位图重绘。相反的,contentMode属性决定了这个位图会如何显示,是进行缩放以适应新的尺寸,或者只是简单的与某一个边缘或者顶点对齐。

当做以下操作都会使得contentMode属性生效:

  • 修改view的frame或者bounds属性的width或者height
  • 给view的transform赋一个具有缩放动作的值

系统提供了如下的属性

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,
};

contentMode的默认属性是UIViewContentModeScaleToFill,这个属性使得contents进行缩放以适应新的frame。
下图展示了不同的属性所产生的效果:

scale_aspect.jpg

由图中看到UIViewContentModeScaleToFill属性会导致形变。而
UIViewContentModeScaleAspectFill导致内容不能完全展示.

content modes是界面重用内容的好方法,当然你也可以设置UIViewContentModeRedraw,使得你的自定义界面在尺寸变化时强制重绘。当设置contentModel属性为UIViewContentModeRedraw后,在view尺寸变化时,系统会强制调用drawRect:方法。一般来说,你应该尽可能的避免使用这个值,并且确保没有给系统标准view设定这个值。

参考###

View and Window Architecture

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容