使用UIBezierPath的角半径

我正在尝试使用“UIBezierPath”围绕我的视角。 我只需要围绕topRight和左上角。

我使用了以下代码

-(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; } 

在此处输入图像描述

但我的TopRight角落不圆。

我用过

UIRectCornerAllCorners

但它并没有围绕我的右角

在此处输入图像描述

我错过了什么?

我建议不同的方法。 加载带圆角顶角和图像的图像作为CALayer内容。 将此图层设置为视图图层的蒙版。 更新给定视图的layoutSubivews中的遮罩层大小或给定视图控制器的viewDidLayoutSubviews

加载图像作为图层最有效

 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 

[编辑]在评论中回答您的问题

无论是使用CAShapeLayer还是使用图像作为遮罩,都必须调整遮罩层的大小,使其与遮罩层的大小相同。 如果我们在谈论UITableViewCell请在layoutSubviews创建自己的派生单元格并更新掩码形状。 下面是示例代码(从故事板加载MyTableCell):

 @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 

我正在使用这个子类

。H

 @interface UIView (custom) - (UIView *)setRoundedCorners:(UIRectCorner)corners withRadius:(CGFloat)radius; @end 

.M

 @implementation UIView (custom) - (UIView *)setRoundedCorners:(UIRectCorner)corners withRadius:(CGFloat)radius { UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)]; CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.frame = self.bounds; maskLayer.path = maskPath.CGPath; self.layer.mask = maskLayer; return self; } @end 

使用它像:

 [YOURVIEW setRoundedCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerTopLeft | UIRectCornerTopRight withRadius:15];