bobbypage
bobbypage

Reputation: 2169

How to set alpha of uiclearcolor?

I am currently doing this:

UIColor *myColor = [UIColor clearColor]; 

This is great but i would like to specify a certain alpha of "myColor". How would i do so?

Upvotes: 38

Views: 27708

Answers (6)

Muhammad Asyraf
Muhammad Asyraf

Reputation: 1808

To answer that Question

UIColor *myColor = [[UIColor clearColor] colorWithAlphaComponent:0.3f];

I assume that you have "clearColor" as a valid UIColor;

@refer James O'Brien Solution;

Upvotes: 1

Gerrit Post
Gerrit Post

Reputation: 1267

For Swift you can use:

UIColor.black.withAlphaComponent(0.5)

Or RGB Colors:

UIColor(red: 0/255.0 , green: 0/255.0 , blue: 0/255.0 , alpha: 0.5)

Upvotes: 7

Cihat Gündüz
Cihat Gündüz

Reputation: 21468

If you prefer a simple and yet powerful solution in Swift then checkout HandyUIKit. Install it in your project using Carthage – then your life becomes easier:

import HandyUIKit

// creates a new UIColor object with the given value set
myColor.change(.alpha, to: 0.2)

There is also an option to apply a relative change:

// create a new UIColor object with alpha increased by 0.2
myColor.change(.alpha, by: 0.2)

I hope it helps!

Upvotes: 0

James O'Brien
James O'Brien

Reputation: 1706

If you have an existing color, you can return a new one with a specified alpha, like this:

- (void)setBackgroundColor:(UIColor *)color 
{
    self.backgroundColor = [color colorWithAlphaComponent:0.3f];
}

Upvotes: 127

E.M.
E.M.

Reputation: 4547

You can use colorWithWhite:alpha like so:

[UIColor colorWithWhite:1.0 alpha:0.5];

Or if you want a specific color:

[UIColor colorWithRed:1.0 green:1.0 blue:0.3 alpha:0.72];

Check out the docs.

Upvotes: 12

ohhorob
ohhorob

Reputation: 11805

[UIColor clearColor] is, how should I put it?, clear!

It is a convenience class method returning a UIColor with alpha at zero.

If you want a color with a fractional amount of transparency:

+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha

Or one of the other UIColor class methods.

Upvotes: 12

Related Questions