问题
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