iOS開發-Alpha,Hidden與Opaque區別

UIView中的這三個屬性用的比較多,尤爲是Alpha和Opaque之間有的時候不是很好分別,稍微整理下:html

Alpha(不透明度)

alpha是不透明度,屬性爲浮點類型的值,取值範圍從0到1.0,表示從徹底透明到徹底不透明,其特性有當前UIView的alpha值會被其全部subview繼承。alpha值會影響到UIView跟其全部subview,alpha具備動畫效果。當alpha爲0時,跟hidden爲YES時效果同樣,可是alpha主要用於實現隱藏的動畫效果,在動畫塊中將hidden設置爲YES沒有動畫效果。ios

 

    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(30, 100, CGRectGetWidth(self.view.bounds)-60, 150)];
    [view setBackgroundColor:[UIColor redColor]];
    [view setAlpha:0.5];
    [self.view addSubview:view];
    
    UIView *childView=[[UIView alloc]initWithFrame:CGRectMake(20, 30, 100, 80)];
    [childView setBackgroundColor:[UIColor blueColor]];
    [view addSubview:childView];

 

設置backgroundColor的alpha值隻影響當前UIView的背景,並不會影響其全部subview。Clear Color就是backgroundColor的alpha爲1.0。alpha值會影響backgroundColor最終的alpha,假設UIView的alpha爲0.8,backgroundColor的alpha爲0.5,那麼backgroundColor最終的alpha爲0.4(0.8*0.5)。app

Hidden(隱藏)

Hidden表示UIView是否隱藏,Hidden設置爲YES表示前UIView的全部subview也會被隱藏,忽略subview的hidden屬性。Hidden只要設置爲YES,全部的subview都會隱藏。UIView隱藏以後也會從當前的響應者事件中移除。ide

Opaque

opaque也是表示當前的UIView的不透明度,設置是否以後對於UIView的顯示並無什麼影響,官方文檔的意思簡單點說就是opaque默認爲YES,若是alpha小於1,那麼應該設置opaque設置爲NO,可是若是alpha爲1,opaque設置爲NO,產生的後果是不可預料的~性能

 

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.

 

若是瞭解opaque,須要點屏幕繪製的知識,屏幕上的每一個像素點都是經過RGBA值(Red、Green、Blue三原色再配上Alpha透明度)表示的,當紋理(UIView在繪圖系統中對應的表示項)出現重疊時,GPU會按照Result = Source + Destination * (1 - SourceAlpha)公式計算重疊部分的像素。動畫

Result是結果RGB值,Source爲處在重疊頂部紋理的RGB值,Destination爲處在重疊底部紋理的RGB值。this

當SourceAlpha爲1時,繪圖系統認爲下面的顏色所有被遮蓋住了,Result=Source,若是Source的Alpha不爲0,上下層顏色就會進行合成,因此opaque默認設置YES,提高繪製性能,若是開發中UIView是不透明的,opaque設置爲YES, 若是opaque設置NO,那麼Alpha應該小於1.spa

參考資料:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/opaqueorm

相關文章
相關標籤/搜索