Pavel
Pavel

Reputation: 167

Creating a rounded-corner view

Good day!

Im trying to make my view (view in main view) make rounded corner. Im doing like this, but it doesn't work. Any ideas?

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
    currenView = [[UIView alloc] init]; 

    UIBezierPath *maskPath;
    maskPath = [UIBezierPath bezierPathWithRoundedRect:currenView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(30.0, 30.0)];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = currenView.bounds;
    maskLayer.path = maskPath.CGPath;
    currenView.layer.mask = maskLayer;


}
return self;

Upvotes: 6

Views: 7410

Answers (4)

NaXir
NaXir

Reputation: 2413

Here is the code. Alloc init a view and send to this method to get corners rounded. You can optionally round any of the corners u want. Also give shadow stroke color.

-(void) setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners withColor:  (UIColor*) color
{
 UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds  byRoundingCorners:corners cornerRadii:CGSizeMake(9.0, 9.0)];

CAShapeLayer* shape = [[[CAShapeLayer alloc] init] autorelease];
[shape setPath:rounded.CGPath];
shape.strokeColor = [[UIColor grayColor] CGColor];

view.backgroundColor=color;
view.layer.mask = shape;
}

Call the method like this.

[self setMaskTo:ABCView byRoundingCorners:UIRectCornerAllCorners withColor:[UIColor greenColor]];

Upvotes: 2

karim
karim

Reputation: 15589

Your view has no size. its w and h is 0. Try something like,

currentView = [[UIView alloc] initWithFrame:CGRectMake(0,0 200,200)]; 

and then apply

currentView.layer.cornerRadius = 8.0;
currentView.layer.masksToBounds = YES;
currentView.layer.borderWidth = 1.0; 

Upvotes: 0

Stavash
Stavash

Reputation: 14304

Try something like this:

view.layer.cornerRadius = 5.0;
view.layer.masksToBounds = YES;

for shadow:

view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
view.layer.masksToBounds = NO;
view.layer.shadowRadius = 5.0f;

Make sure to import <QuartzCore/QuartzCore.h>

Upvotes: 13

Yunus Nedim Mehel
Yunus Nedim Mehel

Reputation: 12369

Stavash's solution seems to be correct, I have used it several times. If you are looking for an alternative or insist on using masklayers, see this answer: https://stackoverflow.com/a/13163693/936957

Upvotes: 0

Related Questions