bezierPathWithRoundedRect不是完美的圆圈

时间:2015-03-15 17:15:00

标签: ios objective-c uiview core-graphics geometry

我对绘制圆圈有一些问题:

这个简单的代码演示了:

- (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"];

}

我们有结果

enter image description here 前三个圆圈按上面的方法绘制,最后一个圆圈我在PS中绘制。 如果你可以看到bezierPathWithRoundedRect绘制不完美的圆与正确的半径我认为(一些角添加到圆)。如何在图片中绘制像圆圈一样的圆圈?

PS:我需要为我的项目使用bezierPathWithArcCenter,但是当我重用bezierPathWithRoundedRect时,我遇到了同样的问题!

3 个答案:

答案 0 :(得分:1)

您需要将+ (NSBezierPath *)bezierPathWithOvalInRect:(NSRect)aRect用于圆圈。

根据定义,RoundedRect是方形的。

答案 1 :(得分:0)

要绘制圆圈,您需要使用圆弧。

查看appendBezierPathWithArcFromPoint:toPoint:radius:

Ovals are not ellipses(虽然它们通常可以互换使用英语)。椭圆是一个概括圆。

答案 2 :(得分:0)

我找到的最佳结果是在CGContextAddEllipseInRect:

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