How to draw a concentric circle in iphone?

2020-05-27 08:30发布

问题:

I want to draw a ring. Ring should filled in a outer circle. I referred a documentation http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_paths/dq_paths.html#//apple_ref/doc/uid/TP30001066-CH211-TPXREF101. But still had problem to get the outcome. Here is the code.

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, rect);
CGContextSetRGBFillColor(ctx, 0.0, 255.0, 1.0, 1.0);CGContextFillPath(ctx);
CGContextStrokeEllipseInRect(ctx, CGRectMake(125, 125, 150, 150));
CGContextBeginPath(ctx);
CGContextEOFillPath(ctx);
CGContextFillEllipseInRect(ctx, CGRectMake(100, 100, 200, 200));

回答1:

You need something more like this:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(ctx, rect);
    CGContextAddEllipseInRect(ctx, 
                CGRectMake(
                    rect.origin.x + 10, 
                    rect.origin.y + 10, 
                    rect.size.width - 20, 
                    rect.size.height - 20));
    CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
    CGContextEOFillPath(ctx);
}

This will add two ellipses to your current path (one being smaller than the other, but centered around the same point). EOFillPath will essentially "subtract" the inner ellipse from the outer ellipse when it fills the path.

To create "concentric" circles, if that's really what you wanted, you can simply repeat this for more - continually smaller - ellipses.