Dekaron
Dekaron

Reputation: 19

How could I draw an ellipse pixel by pixel using CoreGraphics on iPhone

I want to draw an ellipse on the iPhone, and I want to see it draw process, just like we use the pen draw an ellipse on a sheet of paper. I have to draw it pixel by pixel, and don't use CGContextAddEllipseInRect. How could I do it?

Upvotes: 2

Views: 1122

Answers (2)

Jilouc
Jilouc

Reputation: 12714

If you are targeting iOS 4.2 and later, you could use the new property strokeEnd of CAShapeLayer.

Basically, a CAShapeLayer draws the path you supply. Using a CABasicAnimation on its strokeEnd property, you can animate the drawing of the path from one point to another.

CGPoint ellipseOrigin = CGPointMake(50, 50);
CGSize ellipseSize = CGSizeMake(200, 100);

CGRect rect = (CGRect){CGPointZero, ellipseSize};
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, rect);   

CAShapeLayer *ellipseLayer = [CAShapeLayer layer];
ellipseLayer.frame = (CGRect){ellipseOrigin, ellipseSize};
ellipseLayer.path = path;
ellipseLayer.strokeColor = [UIColor blackColor].CGColor;
ellipseLayer.fillColor = nil; // transparent inside

CFRelease(path);

// I tested it in the viewDidLoad method of a view controller
[self.view.layer addSublayer:ellipseLayer];

CABasicAnimation *drawAnim = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnim.duration = 5.0;
drawAnim.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnim.toValue = [NSNumber numberWithFloat:1.0f];
[ellipseLayer addAnimation:drawAnim forKey:@"strokeEnd"];

I initially learned how to do this thanks to this post on Ole Begemann's blog: Animating the drawing of a CGPath with CAShapeLayer.

Upvotes: 1

James Bedford
James Bedford

Reputation: 28962

I'm not sure if this is the best way, but I would suggest using quadratic bezier curves and some form of animation to draw a different curve at each frame. You need to set up the animation using an NSTimer or something, and then call setNeedsRedisplay on the object that draws the "circle" each time the timer fires, also updating the current timestep of the animation draw object so it knows which frame to calculate and draw.

At each redraw, a calculation needs to be made to draw the required curve that you need to progress a step further in the animation. You can use the quartz method CGContextAddQuadCurveToPoint() to draw the curve. You will need two curves to complete the whole effect (one will be used for the first half of the animation, and one will be used for the second half).

I hope this provides a few initial thoughts.

Upvotes: 0

Related Questions