天天看点

iOS开发-Opaque、Alpha、Hidden区别1、Alpha(不透明度)2、Hidden(隐藏)3、Opaque(不透明的)

在UIView中,有段时间Alpha,Hidden用的比较多,Opaque是最近才了解的,感觉有些不好理解于是就将这三个属性做了区分:

属性:

  • 1、Alpha(不透明度)
  • 2、Hidden(隐藏)
  • 3、Opaque(不透明的)

1、Alpha(不透明度)

1.1、alpha是不透明度,属性为浮点类型的值,取值范围从0~1.0,表示从完全透明到完全不透明。

1.2、当前UIView的alpha值会被其所有subview继承,即当前UIView的alpha值会影响到其所有subview。

1.3、当alpha为0时,跟hidden为YES时效果一样,但是alpha主要用于实现隐藏的动画效果,在动画块中将hidden设置为YES没有动画效果。

1、backgroundColor的alpha值只影响当前UIView的背景,并不会影响其所有subview。

2、Clear Color就是backgroundColor的alpha为1.0。

3、alpha值会影响backgroundColor最终的alpha。

假设UIView的alpha为0.8,backgroundColor的alpha为0.5,那么backgroundColor最终的alpha为0.4(0.8*0.5)。

2、Hidden(隐藏)

Hidden表示UIView是否隐藏,Hidden设置为YES表示当前UIView的所有subview也会被隐藏,忽略subview的hidden属性。

Hidden只要设置为YES,所有的subview都会隐藏。

UIView隐藏之后也会从当前的响应者事件中移除。

3、Opaque(不透明的)

opaque表示当前的UIView的不透明度,设置是否之后对于UIView的显示并没有什么影响,官方文档的意思简单点说:opaque默认为YES,如果alpha小于1,那么应该设置opaque设置为NO,但是如果alpha为1,opaque设置为NO,产生的后果是不可预料的~

作用原理:

1、给绘图系统提供一个性能优化的开关, UIView 默认为 YES, UIButton 等默认为 NO。

2、如果设置为 YES,绘图系统把这个视图当做一个不透明的来对待,这样就会提高性能。

3、如果设置为 NO,绘图系统就会把它和其他的普通view一样来对待,不去做优化操作。

4、所以说应该把 view 的 opaque 设置为 YES.

This property provides a hint to the drawing system as to how it should treat the view. If set to YES, the drawing system treats the view as fully opaque, which allows the drawing system to optimize some drawing operations and improve performance. If set to NO, the drawing system composites the view normally with other content. The default value of this property is YES.
 
An opaque view is expected to fill its bounds with entirely opaque content—that is, the content should have an alpha value of 1.0. If the view is opaque and either does not fill its bounds or contains wholly or partially transparent content, the results are unpredictable. You should always set the value of this property to NO if the view is fully or partially transparent.
 
You only need to set a value for the opaque property for subclasses of UIView that draw their own content using the drawRect: method. The opaque property has no effect for system provided classes such as UIButton, UILabel, UITableViewCell, etc.

           

翻译:

这个属性向绘图系统提供了一个提示,说明它应该如何处理视图。如果设置为YES,绘图系统将视图视为完全不透明的,这允许绘图系统优化一些绘图操作并提高性能。如果设置为NO,绘图系统通常会将视图与其他内容组合在一起。此属性的默认值为YES。

一个不透明的视图应该用完全不透明的内容来填充其边界——也就是说,内容的alpha值应该为1.0。如果视图是不透明的,或者没有填充其边界,或者包含全部或部分透明的内容,那么结果是不可预测的。如果视图是完全透明或部分透明的,您应该始终将此属性的值设置为NO。

您只需要为UIView的子类设置一个不透明属性的值,这些子类使用drawRect:方法绘制它们自己的内容。不透明属性对系统提供的类(如UIButton、UILabel、UITableViewCell等)没有影响。

惨开链接:

1、iOS开发-Alpha,Hidden与Opaque区别