bezierPathWithRoundedRect not perfect circle

女生的网名这么多〃 提交于 2020-01-16 06:09:05

问题


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

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!


回答1:


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

By definition a RoundedRect is squarish.




回答2:


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.




回答3:


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();
}


来源:https://stackoverflow.com/questions/29063680/bezierpathwithroundedrect-not-perfect-circle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!