Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust alpha of UIColor

People also ask

What is Alpha in Uicolor?

alpha. The opacity value of the new color object, specified as a value from 0.0 to 1.0.

Is Alpha the same as opacity?

Alpha affects everything drawn on the view. The background color's alpha affects the background color's transparency and anything else drawn on the view. i.e it brings about a frosty effect to whole view. Opacity means don't draw anything underneath, even if you are transparent, it just effects the current view.

What is CGColor in Swift?

CGColor is the fundamental data type used internally by Core Graphics to represent colors. CGColor objects, and the functions that operate on them, provide a fast and convenient way of managing and setting colors directly, especially colors that are reused (such as black for text).


colorWithAlphaComponent: did the trick.

So what I had to do was:

self.mylabel.backgroundColor = [self.myLabel.backgroundColor colorWithAlphaComponent:0.3];

Swift 3+

yourUIView.backgroundColor = UIColor.white.withAlphaComponent(0.75)

Swift 2

yourUIView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.75)

If you have custom colors defined, you can do this as well:

view.backgroundColor = [[MyClass someColor] colorWithAlphaComponent:0.25];

why not using label.alpha = 0.5 ? to adjust your label's alpha?

update: if you want to adjust alpha from a old color, here is an example:

UIColor uicolor = [UIColor greenColor];
CGColorRef color = [uicolor CGColor];

int numComponents = CGColorGetNumberOfComponents(color);

UIColor newColor;
if (numComponents == 4)
{
    const CGFloat *components = CGColorGetComponents(color);
    CGFloat red = components[0];
    CGFloat green = components[1];
    CGFloat blue = components[2];
    newColor = [UIColor colorWithRed: red green: green blue: blue alpha: YOURNEWALPHA];

}

Version Swift (5.4)

UIColor.blue.withAlphaComponent(0.5)

The shortest possible code (Swift 5):

view.backgroundColor = .black.withAlphaComponent(0.75)