126

I set a UIColor using rgb to a background of a UILabel. I'm trying to adjust the alpha only. How can I modify the alpha of an existing rgb UIColor?

Edit

Basically I have UILabels that have a set UIColor (using rgb), and I won't know what color the UILabels are. At a certain point, I will have to change the labels alpha`. How can I just change the labels color alpha?

Eric
  • 3,811
  • 5
  • 15
  • 18

7 Answers7

206

colorWithAlphaComponent: did the trick.

So what I had to do was:

self.mylabel.backgroundColor = [self.myLabel.backgroundColor colorWithAlphaComponent:0.3];
pkamb
  • 33,281
  • 23
  • 160
  • 191
Eric
  • 3,811
  • 5
  • 15
  • 18
  • is there any difference between this approach and say this? `UIColor(red:0.07, green:0.44, blue:0.54, alpha:0.4)` – Changerrs Sep 18 '17 at 17:58
  • 2
    @Changerrs : there can be cases when we need to apply alpha to a existing color. ie existing colors cant not be modified. Hence for such cases we already have a color value, but then need to apply alpha to it hence colorWithAlphaComponent comes handy for such case. – Bishal Ghimire Dec 10 '17 at 03:42
106

Swift 3+

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

Swift 2

yourUIView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.75)
Yoav
  • 5,962
  • 5
  • 39
  • 61
GraSim
  • 3,830
  • 1
  • 29
  • 35
15

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

view.backgroundColor = [[MyClass someColor] colorWithAlphaComponent:0.25];
chris g
  • 1,088
  • 10
  • 18
10

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];

}
JZAU
  • 3,550
  • 31
  • 37
10

Version Swift (5.4)

UIColor.blue.withAlphaComponent(0.5)
Peter Suwara
  • 781
  • 10
  • 16
5

The shortest possible code (Swift 5):

view.backgroundColor = .black.withAlphaComponent(0.75)
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194
0

Please set alpha in below code -

[UIColor colorWithRed:200.0/255.0 green:191.0/255.0 blue:231.0 /255.0 alpha:1.0]
Santu C
  • 2,644
  • 2
  • 12
  • 20