Mohanad S. Hamed
Mohanad S. Hamed

Reputation: 301

How to create transparent UIView with non-transparent border

I am trying to make a transparent UIView with a border. The problem is that the border will always be transparent, how can I make it non-transparent?

This is my code

- (void) viewDidLoad:(BOOL)animated
{

  [super viewDidLoad:animated]; 

  _transparentView.alpha = 0.5f;
  _transparentView.layer.borderColor = [UIColor whiteColor].CGColor;
  _transparentView.layer.borderWidth = 2.0f;
}

Upvotes: 0

Views: 2882

Answers (4)

mikeho
mikeho

Reputation: 7000

Just set the background to a clear color:

// set the border color
_transparentView.layer.borderColor = [UIColor whiteColor];
// set the border width
_transparentView.layer.borderWidth = 3.0f;
// want rounded corners? set this
_transparentView.layer.cornerRadius = 5.0f;

// make the background clear color to be fully transparent
_transparentView.backgroundColor = [UIColor clearColor];

You don't need subviews or anything else.

Upvotes: 2

Hiren
Hiren

Reputation: 12780

-(void)setRoundedView:(UIView *)vW{
    CALayer *image = vW.layer;
    [image setCornerRadius:5];
    [image setBorderWidth:1];
    image.masksToBounds = YES;
    image.borderColor = [UIColor colorWithRed:202.0/255.0 green:202.0/255.0 blue:202.0/255.0 alpha:1].CGColor;
}

Upvotes: 1

Niels
Niels

Reputation: 583

You can achieve this by setting the backgroundColor of the view to a transparent color:

_transparentView.backgroundColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.5];
_transparentView.layer.borderColor = [UIColor whiteColor].CGColor;
_transparentView.layer.borderWidth = 2.0f;

This will make the background of the view a transparent green.

Upvotes: 2

Rajesh
Rajesh

Reputation: 960

You can do it by adding transparent view to as a sub-view of another view like as bellow

_transparentView.alpha = 0.5f;

_MainView.backgroundColor = [UIColor clearColor];
_MainView.layer.borderColor = [UIColor whiteColor].CGColor;
_MainView.layer.borderWidth = 2.0f;
[_MainView addSubview:_transparentView];

Upvotes: 2

Related Questions