Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Corner Radius Using UIBezierPath

I'm Trying to round my view's corners using "UIBezierPath". I Only need to round topRight and Top left.

I have used Following code

 -(void)setMaskOnView:(UIView *)givenView
  {
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:givenView.bounds byRoundingCorners: (UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = givenView.bounds;
maskLayer.path  = maskPath.CGPath;
givenView.layer.mask = maskLayer;
} 

enter image description here

But my TopRight Corner does not round.

I've used

UIRectCornerAllCorners

But it does not round my right corners

enter image description here

Any thing i'm missing??

like image 231
Arslan Asim Avatar asked Mar 30 '26 15:03

Arslan Asim


1 Answers

I suggest different approach. Load image with rounded top corners and set is as contents of CALayer. Set this layer as mask of your view layer. Update size of your mask layer in layoutSubivews of a given view or viewDidLayoutSubviews of given view controller.

Loading image as layer contenst

CALayer *maskLayer = [[CALayer alloc] init];
UIImage *maskImage = [UIImage imageNamed:@"mask_image.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
maskLayer.contents = (__bridge id _Nullable)(maskImage.CGImage);

mainLayer.mask = maskLayer

[EDIT] Answering your questions in comments

Either using CAShapeLayer or image as mask you have to resize your mask layer so it will have the same size as masked layer. If we are talking about UITableViewCell create your own derived cell and update mask shape in layoutSubviews . Below is example code (MyTableCell is loaded from storyboard):

@interface MyTableCell ()

@property (nonatomic, strong) CAShapeLayer *maskLayer;

@end

@implementation MyTableCell

- (void)awakeFromNib
{
    self.maskLayer = [[CAShapeLayer alloc] init];
    self.layer.mask = self.maskLayer;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.maskLayer.path = [self maskPath].CGPath;
}

- (UIBezierPath *)maskPath
{
    return [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners: (UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)];

}

@end
like image 109
MichK Avatar answered Apr 02 '26 08:04

MichK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!