【问题标题】:UIView roundedCorners and UIBezierPath bezierPathWithRoundedRect produce slightly different resultsUIView roundedCorners 和 UIBezierPath bezierPathWithRoundedRect 产生略有不同的结果
【发布时间】:2020-11-09 04:58:14
【问题描述】:

我一直在研究使用UIBezierPath 重新创建UIViewcornerRadius 行为。我知道bezierPathWithRoundedRect 方法,在我看来,这是实现相同结果的最干净的方法。

但是,对比两种方法的结果后,两者在视觉上似乎略有不同,我不明白这是为什么。

这里是代码 sn-ps 和图片: UIView +cornerRadius + backgroundColor:

UIView *foo = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
foo.backgroundColor = UIColor.blueColor;
foo.layer.cornerRadius = 50;
[self.view addSubview foo];

CALayer + bezierPathWithRoundedRect + addSublayer:

UIView *foo = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
CAShapeLayer *bar = [CAShapeLayer layer];
bar.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 100, 100) 
                                      cornerRadius:50].CGPath;
bar.fillColor = UIColor.blueColor.CGColor;
[foo.layer addSublayer:bar];
[self.view addSubview:foo];

CALayer + bezierPathWithRoundedRect + 蒙版:

UIView *foo = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
CAShapeLayer *bar = [CAShapeLayer layer];
bar.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 100, 100) 
                                      cornerRadius:50].CGPath;
bar.fillColor = UIColor.clearColor.CGColor;
foo.backgroundColor = UIColor.blueColor;
foo.layer.mask = bar;
[self.view addSubview:foo];

虽然两种 bezierPath 方法(添加为子图层或遮罩)生成完全相同的图像,但它们都不同于 UIView +cornerRadius 方法。

这是可视化的差异:

我尝试过的:

  • 我尝试发出 shouldRasterize,但这只会造成更大的差异和更模糊。
  • 我尝试使用 CGPathAddArcToPoint 的正确角度手动计算 CGPath,但它产生的结果与使用 bezierPathWithRoundedRect 相同。
  • 我尝试使用 fillRule 作为 kCAFillRuleEvenOdd。
  • 我尝试将allowEdgeAntialiasing设置为YES。
  • 我尝试使用 UIBezierPath.init(roundedRect: CGRect, byRoundingCorners: UIRectCorner,cornerRadii: CGSize) 和 UIBezierPath.init(arcCenter:radius:startAngle:endAngle:顺时针:) 创建圆,但视觉结果仍与 bezierPathWithRoundedRect 相同李>

任何帮助将不胜感激!

为了生成这些图像,我在 iOS 13.5 模拟器上使用 Xcode 11.5 和 iPhone SE(第二代)。

【问题讨论】:

    标签: ios uikit calayer uibezierpath cornerradius


    【解决方案1】:

    【讨论】:

    • 不幸的是,设置属性后,它并没有在视觉上改变图像:(感谢分享!
    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2014-09-03
    • 2018-05-23
    • 2017-09-11
    相关资源
    最近更新 更多