What's the relationship among opaque, alpha, and backgroundColor of a UIView?

Emily picture Emily · Jan 12, 2012 · Viewed 8.2k times · Source

For example:

  1. I set UIView's alpha property as alpha = 0, Does that means its opaque property be treated as opaque=YES?

  2. How opaquealpha and backgroundColor affect the performance?

  3. Anything else?...

Similar Questions

Answer

bryanjclark picture bryanjclark · Feb 2, 2012

backgroundColor is the color that appears in the back of a UIView. By default, it's nil, resulting in a clear background color for the UIView. To assign a background to your UIView, assign a UIColor like so:

myView.backgroundColor = [UIColor greenColor];

You can also set the backgroundColor to be an image:

myView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed@"myImage"]];

alpha is the opacity of the view. You can use this attribute to fade a UIView and make it partially transparent. The value can range from 0 (completely invisible) to 1 (completely opaque).


opaque is a boolean value that indicates whether the UIView is opaque or not. If you've set the alpha to anything less than 1, then you should set opaque to NO:

myView.opaque = NO;

Apple's documentation explains why and how the opaque property works:

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.