bezierPathWithRoundedRect not perfect circle

2019-08-11 09:08发布

I have some problem with draw circle:

This simply code demonstrates that:

- (void)drawRect:(CGRect)rect {

    self.layer.sublayers = nil;
    CGFloat radius = self.frame.size.width/2;

    circle = [CAShapeLayer layer];
    circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.width) cornerRadius:radius].CGPath;

    circle.fillColor = [UIColor clearColor].CGColor;
    circle.strokeColor = [UIColor redColor].CGColor;

    circle.lineWidth = 4;

    [self.layer addSublayer:circle];

    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];

    drawAnimation.duration            = 1.0; // "animate over 10 seconds or so.."
    drawAnimation.repeatCount         = 1.0;  // Animate only once..

    drawAnimation.fromValue = [NSNumber numberWithFloat:0];
    drawAnimation.toValue   = [NSNumber numberWithFloat:1];

    drawAnimation.removedOnCompletion = NO;
    drawAnimation.fillMode = kCAFillModeForwards;

    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    drawAnimation.delegate = self;
    [circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];

}

And we have result

enter image description here First three circles draws by method above, last circle I draw in PS. If u can see bezierPathWithRoundedRect draws not perfect circle with right radius I think (some corners added to circle). How to draw circle like last circle in a picture?

PS: I need to use bezierPathWithArcCenter for my project, but when I reuse bezierPathWithRoundedRect I has same problem!

3条回答
神经病院院长
2楼-- · 2019-08-11 09:52

You need to use + (NSBezierPath *)bezierPathWithOvalInRect:(NSRect)aRect for a circle.

By definition a RoundedRect is squarish.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-11 10:00

The best result I found was to use CGContextAddEllipseInRect: in drawRect:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect boundingRect = CGRectMake(2.0f, 2.0f, CGRectGetWidth(self.bounds)-4.0, CGRectGetHeight(self.bounds)-4.0);
    CGContextSetLineWidth(context, 3.0);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextBeginPath(context);
    CGContextAddEllipseInRect(context, boundingRect);
    CGContextDrawPath(context, kCGPathFillStroke);
    UIGraphicsEndImageContext();
}
查看更多
Evening l夕情丶
4楼-- · 2019-08-11 10:08

To draw circles you need to use arcs.

Look at appendBezierPathWithArcFromPoint:toPoint:radius:

Ovals are not ellipses (although they are commonly used interchangeably in English). Ellipse is a generalise circle.

查看更多
登录 后发表回答