使用UIBezierPath创建圆角的半径

3
我将尝试使用“UIBezierPath”来圆角化我的视图。我只需要圆角化右上角和左上角。
我已经使用了以下代码:
 -(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;
} 

这里输入图片描述

但是我的右上角没有圆角。

我使用了

UIRectCornerAllCorners

但它没有使我的右侧角变圆。

这里输入图片描述

我有什么遗漏的吗?


1
你在哪里调用 setMaskOnView 函数?很可能是在布局完成之前。因此,边界尚未正确设置,将会/已经发生变化。 - luk2302
将 givenView.bounds 更改为 givenView.superview.bounds 并检查是否有效。 - Parth Bhadaja
@luk2302 我在viewDidLoad中调用它。 - Arslan Asim
2
那个位置是错误的,每当布局发生变化时,您都必须设置掩码。 - luk2302
如果我需要四舍五入 TableViewCell,什么时候打电话最好呢? - Arslan Asim
显示剩余2条评论
2个回答

1
我建议采用不同的方法。加载带有圆角顶部的图像,并将其设置为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

0

我正在使用这个子类

.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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接