diablo1234
diablo1234

Reputation: 409

Making UIView transparent

I want to add a UIView to my UIViewController but I want it to be transparent until I decide to create an Oval inside the UIView.

Until I create the oval, I can set my view's alpha to 0 but when I want to add the oval, the background color is still black.

here's what it looks like with a bunch of ovals

image

In my UIView:

- (void)drawRect:(CGRect)rect
{
    [self pushContext];
    UIBezierPath *oval = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
    [[UIColor redColor] setFill];
    [oval fill];
    self.opaque = NO;
    [self setBackgroundColor:[UIColor clearColor]];

    [oval addClip];
    [self setBackgroundColor:[UIColor clearColor]];

    [self popContext];
}

Upvotes: 22

Views: 47072

Answers (5)

Northern Captain
Northern Captain

Reputation: 1237

I did semi-transparent background for my UIViewController the same way as it's recommended here but it didn't work until I set modalPresentationStyle to .custom

my Swift 4 code:

modalPresentationStyle = .custom
view.isOpaque = false
view.backgroundColor = UIColor.black.withAlphaComponent(0.2)

I open my controller from another one using present(controller, anim, completion) method.

Upvotes: 5

Matt
Matt

Reputation: 693

In Swift 3.x: (where layer is the view)

layer.backgroundColor = UIColor.clear.cgColor
layer.isOpaque = false

Upvotes: 3

Natasha
Natasha

Reputation: 6903

In your ViewController, you could say that opaque is NO. Let's say, your view is named myCustomView.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myCustomView.opaque = NO;   
}

Or you could just go to the storyboard and uncheck the opaque checkbox like- enter image description here

Upvotes: 5

Guo Luchuan
Guo Luchuan

Reputation: 4731

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        self.opaque = NO;

    }
    return self;
}



- (void)drawRect:(CGRect)rect
{
    [[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0] setFill];
    UIRectFill(rect);
    [self pushContext];
    UIBezierPath *oval = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
    [[UIColor redColor] setFill];
    [oval fill];

    [oval addClip];

    [self popContext];
}

Upvotes: 19

Dharmbir Singh
Dharmbir Singh

Reputation: 17535

Please try to use this one

view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
view.opaque = NO;

Upvotes: 29

Related Questions