Ivan Slavka
Ivan Slavka

Reputation: 11

How to perform animation in objective c

I'm trying to learn how to animate motion of the circle that I created in custom View. However, during the loop in startMovingCircle the circle doesn't show, it appears only when the loop finishes. I thought that if I call setNeedsDisplay every time it should redraw the view and the animation of moving circle should show up. Could someone tell me what am I doing wrong?

Also, I would like to ask if it is correct to program animation this way or should I use CoreAnimation and what are the benefits? Can CoreAnimation animate shapes like circle, elipses, rectangle programmed in CoreGraphics?

MyDrawingView.m:

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        xCoordinate = 100.0;
        yCoordinate = 100.0;
        speed = 1.0;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    NSLog(@"Drawing");
    CGContextRef myContext =  UIGraphicsGetCurrentContext();
    CGContextBeginPath(myContext);
    CGContextAddArc(myContext, xCoordinate, yCoordinate, 20.0, 0.0, 2 * M_PI, 0);
    CGContextClosePath(myContext);

    CGContextSetLineWidth(myContext, 1);
    CGContextSetStrokeColorWithColor(myContext, [UIColor whiteColor].CGColor);
    CGContextStrokePath(myContext);
}

-(void)moveCircle{
    xCoordinate += speed;
    yCoordinate += speed;
    NSLog(@"Moving circle. X: %f, Y: %f", xCoordinate, yCoordinate);
    [self setNeedsDisplay];
} 

MyDrawingViewController.m:

-(void)startMovingCircle{
    for(int i = 0; i < 1000; i++){
        [myView moveCircle];
    }
}

Upvotes: 0

Views: 102

Answers (2)

AlexWien
AlexWien

Reputation: 28727

in -(void)moveCircle

you should create a core animation (with blocks) and animate the center property of the view to animate.

Upvotes: 2

Daddy
Daddy

Reputation: 9035

You should add a pause in between iterations of your for() loop.

Upvotes: -1

Related Questions