iOS 7上疯狂的圆角矩形UIBezierPath行为。如何处理?

Ste*_*veo 5 drawing objective-c cgcontext ios uibezierpath

下面的简单UIView绘制了一个圆角矩形。当我通过65或以下的拐角半径时,它会正确倒圆,但在66或以上时会产生一个完美的圆!这里发生了什么?仅当拐角半径等于框架宽度的1/2时,才应显示一个圆,但无论视图大小如何,似乎在半径约为1/3时都将绘制一个圆。此行为出现在iOS 7上。在iOS 6上,我得到了预期的行为。

#import "ViewController.h"
@interface MyView : UIView
@end

@implementation MyView
-(void)drawRect:(CGRect)rect {
  UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 200, 200) cornerRadius:65];
  CGContextRef c = UIGraphicsGetCurrentContext();
  CGContextAddPath(c, path.CGPath);
  [[UIColor redColor] set];
  CGContextStrokePath(c);
}
@end

@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  MyView *v = [[MyView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
  [self.view addSubview:v];
}
@end
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 在此处输入图片说明

在此处输入图片说明

小智 2

这可能永远不会被修复。这就是原因。

计算是否可以制作方圆的数学公式是:radius * magicMultiplier * 2。如果结果比边长,则无法形成方格,因此会形成圆形。

magicMultiplier是必需的,因为要使其看起来像方圆,贝塞尔曲线需要从比半径更长的距离开始。魔法乘数提供了额外的距离。

根据我的研究和对贝塞尔函数的使用,我相信神奇的乘数可能是存在的1.0 + 8.0 / 15.0 = 1.533

比最短边 (200) 长的长度也是如此,因此它成为一个66*(1+8/15)*2圆。202.4

然而!65*(1+8/15)*2199.33小于 200,所以它正确地旋转它。

可能的解决方案

  1. 编写您自己的贝塞尔曲线函数(或在线获取一个)
  2. 使用视图的layer.cornerRadius 可以实现同样的效果,因为Apple 在这里不限制圆角半径。
layer.cornerCurve = .continuous
layer.cornerRadius = min(radius, min(bounds.width, bounds.height)/2.0)
// You might want to clamp it yourself
Run Code Online (Sandbox Code Playgroud)

请记住,这draw(in ctx)不适用于layer.maskedCorners. 所以你不能将 SnapshotTesting 与这些一起使用。