Reputation: 185
I can successfully compiled and run the Hello World code. Now I want to do something like animation.
I first create a rectangle class to implement draw() from Fl::widget
class myRect: public Fl_Widget {
private:
Fl_Color color;
void draw(){
fl_color(color);
fl_rectf(x(),y(),w(),h(),color);
}
public:
myRect(int X,int Y,int W,int H, Fl_Color c) : Fl_Widget(X,Y,W,H),color(c) {}
};
int main (int argc, char ** argv)
{
Fl_Window *window = new Fl_Window (300, 180, "FLTK Test");
vector<myRect*> allRect;
for(int i=0; i<10; ++i){
allRect.push_back(new myRect ((i*10)%100,100,50,50,i%256));
}
window->end();
window->show();
return Fl::run();
}
The code above can run as I expected. But Now I want to show the rectangles one by one, with some time interval such as 1 second. Make it just like animation.
I have read the official document but I still have no idead about that. Please give me some information. Thanks !!
Thanks to DejanLekic, I revised my code as below:
#include <iostream>
#include <vector>
#include <FL/Fl.H>
#include <FL/Fl_Widget.H>
#include <FL/Fl_Double_Window.H>
#include <FL/fl_draw.H>
using namespace std;
class myRect: public Fl_Widget {
private:
Fl_Color color;
void draw(){
fl_color(color);
fl_rectf(x(),y(),w(),h(),color);
}
public:
myRect(int X,int Y,int W,int H, Fl_Color c)
:Fl_Widget(X,Y,W,H),color(c) {}
};
vector<myRect*> allRect;
void winUpdate(void *data)
{
static unsigned i = 0;
Fl_Double_Window *o = (Fl_Double_Window*)data;
if(i < allRect.size()){
o->add(allRect[i]);
if(i>=3) o->remove(allRect[i-3]);
o->redraw();
Fl::add_timeout(0.5,winUpdate,data);
++i;
}
}
int main (int argc, char ** argv)
{
for(int i=0; i<8; ++i){
allRect.push_back(new myRect(i*30,i*30,50,50,i));
}
Fl_Double_Window *window = new Fl_Double_Window (400, 400, "FLTK Test");
Fl::add_timeout(2,winUpdate,window);
window->end();
Fl::visual(FL_DOUBLE|FL_INDEX);
window->show();
return Fl::run();
}
It seems to run well, but I'm not sure whether it is correct or not. If there is any problem, please let me know. Thanks.
Upvotes: 2
Views: 6934
Reputation: 19797
Cory, you are on the right path.
Here is a complete example how to do a simple 2D animation using FLTK's drawing capabilities: http://seriss.com/people/erco/fltk/#AnimateDrawing
Similar thing using OpenGL: http://seriss.com/people/erco/fltk/#OpenGlInterp
The key, in both examples is in the Fl::add_timeout(0.25, Timer_CB, (void*)this);
line, and in the Timer_CB()
static (callback) method. Both examples are nice and easy and I am confident you will understand them instantly.
Upvotes: 1