首页 文章

为什么应用bezierPathWithRoundedRect掩码会产生与设置图层的cornerRadius不同的结果?

提问于
浏览
3

我通常使用 cornerRadius 属性来应用圆角来查看图层 . 当视图只需要圆角顶角或底角时,我应用具有贝塞尔曲线路径的蒙版(使用 bezierPathWithRoundedRect:byRoundingCorners:cornerRadii: ) . 当两种方法在同一视图层次结构中组合时,圆角未正确对齐,如下所示:

Difference in rounded corners

可以使用以下代码重现此简化示例:

@interface ViewController : UIViewController

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    CGRect frame = CGRectMake(50.0, 50.0, 100.0, 100.0);
    CGFloat radius = 20.0;

    // Apply cornerRadius to green backdrop view.
    UIView *backdropView = [[UIView alloc] initWithFrame:frame];
    backdropView.backgroundColor = [UIColor greenColor];
    backdropView.layer.cornerRadius = radius;
    [self.view addSubview:backdropView];

    // Apply bezier path mask to black front view.
    UIView *frontView = [[UIView alloc] initWithFrame:frame];
    frontView.backgroundColor = [UIColor blackColor];
    CAShapeLayer * maskLayer = [CAShapeLayer layer];
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:frontView.bounds
                                           byRoundingCorners:UIRectCornerAllCorners
                                                 cornerRadii:CGSizeMake(radius, radius)].CGPath;
    frontView.layer.mask = maskLayer;
    [self.view addSubview:frontView];
}

@end

设置所涉及的不同层的 shouldRasterize 属性并未解决问题 . 我想明白为什么会这样 . 一个可能的解决方法是始终应用贝塞尔路径掩码,而不是简单地设置角半径,但感觉有点过度 .

1 回答

相关问题