views:

236

answers:

1

When I use GLUT, I can provide a callback function that gets called once per frame to generate or animate the frame content.

How do I do the same thing with Cocoa?

I understand there's setNeedsDisplay, but I don't know how to avoid calling it more than once per frame. What I need is an event or other callback that tells me when to draw another frame.

+3  A: 

Hi Neil,

Everything in Cocoa is buffered, so you can move, animate and adjust views without redrawing them. If you need to redraw a view over and over (for instance, to repeatedly call drawRect: and create your own animation) you need to create a timer that fires every 1/20th of a second and triggers the refresh of the view.

You can create a timer like this:

[NSTimer scheduledTimerWithTimeInterval:1.0/20.0 target:self selector:@selector(animate) userInfo:nil repeats:YES];

Your callback function (in this case "animate") would look like this. If your animation requires business logic, you should put it here. All drawing needs to be done within the view's drawRect function, though.

- (void)animate {
    [animatedView setNeedsDisplay: YES];
}

It's safe to call setNeedsDisplay more than once per frame. SetNeedsDisplay sets a flag on the view and doesn't actually perform any drawing. When your code has executed and the application returns to the main run loop all the views with setNeedsDisplay=YES will be redrawn.

Hope that helps!

Ben Gotow
How do you know that 1/20 second is the correct rate?
Neil Baylis
It really just depends how rapidly you need to animate your view. A frame rate of 24 or 30 fps might be better depending on how smooth you need the animation to be.
Ben Gotow
Well, I want it to be exactly the same as the video refresh rate, so it is as smooth as possible, without ever computing un-necessary frames. Is there a way to get a timer callback once per video frame?
Neil Baylis
Ahh - I see what you're trying to do now! Unfortunately, I don't know too much about that - I've never messed with frame sync. Page 125 in Apple's OpenGL Programming Guide seems to talk about it though: http://developer.apple.com/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/OpenGLProg_MacOSX.pdf. Good luck!
Ben Gotow