Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS controlling UIView alpha behaviour for subviews

Tags:

ios

uiview

alpha

In my example, I have 3 views: one red view containing two white views. I change the red container view's alpha to 0.3 and this happens (look at the image, the current result).

By seeing this, I can only assume (tell me if I'm wrong) that setting a view's alpha will also set all of its subviews' alphas. My question is : is there a way to simply tell the red view to act as a whole so that setting its alpha would give something that looks like the wanted result (in the image)?

results

This is what it looks like without any alpha :

enter image description here

like image 828
Louis Boux Avatar asked Dec 20 '11 21:12

Louis Boux


3 Answers

To elaborate on Mark's answer: If you set UIViewGroupOpacity in the Info.plist, it will change the behavior for all views in your app, if you are interested in only fixing the rendering of this particular view, you could also use this snippet:

redContainerView.layer.shouldRasterize = YES;
// No setting rasterizationScale, will cause blurry images on retina.
redContainerView.layer.rasterizationScale = [[UIScreen mainScreen] scale];
like image 190
Torsten Avatar answered Nov 13 '22 13:11

Torsten


The iOS alpha property is inherited by its subviews. If we are setting alpha 0.3 for red view then both subview will have the alpha = 0.3. There is no way to stop subviews from inheriting their alpha value from their superview.

The solution might be to set the colour of the red view with an alpha of 0.3. The color property will not be inherited by its subview.

[redView setBackgroundColor:[UIColor colorWithHue:238.0f/255.0f saturation:24.0f/255.0f brightness:24.0f/255.0f alpha:0.3]];
like image 34
Nanda Avatar answered Nov 13 '22 15:11

Nanda


Check out the possible UIKit keys for Info.plist, specifically UIViewGroupOpacity.

UIViewGroupOpacity (Boolean - iOS) specifies whether Core Animation sublayers inherit the opacity of their superlayer.

Info.plist UIKit Keys

like image 12
Mark Adams Avatar answered Nov 13 '22 14:11

Mark Adams