Читаем Применение Windows API полностью

What remains is to implement the animation. The naive implementation would be to keep re-drawing the image: background, mask and sprite, changing the position of the mask and the sprite in each frame. The problem with this approach is that it results in unacceptable flutter. The trick with good animation is to prepare the whole picture off-line, as a single bitmap, and then blit it to screen in one quick step. This technique is called double buffering — the first buffer being the screen buffer, the second one — our bitmap.

We'll also use Windows timer to time the display of frames.

class WinTimer {

public:

 WinTimer(HWND hwnd = 0, int id = -1) : _hwnd (hwnd), _id (id) {}

 void Create(HWND hwnd, int id) {

  _hwnd = hwnd;

  _id = id;

 }

 void Set(int milliSec) {

  ::SetTimer(_hwnd, _id, milliSec, 0);

 }

 void Kill() {

  ::KillTimer(_hwnd, _id);

 }

 int GetId() const {

  return _id;

 }

private:

 HWND _hwnd;

 int _id;

};

We'll put the timer in our Controller object and initialize it there.

class Controller {

public:

 Controller(HWND hwnd, CREATESTRUCT* pCreate);

 ~Controller();

 void Timer(int id);

 void Size(int x, int y);

 void Paint();

 void Command(int cmd);

private:

 HWND _hwnd;

 WinTimer _timer;

 View _view;

};


Controller::Controller(HWND hwnd, CREATESTRUCT * pCreate) : _hwnd (hwnd), _timer (hwnd, 1), _view(pCreate->hInstance) {

 _timer.Set (100);

}

Once set, the timer sends our program timer messages and we have to process them.

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {

 Controller* pCtrl = WinGetLong(hwnd);

 switch (message) {

 ...

 case WM_TIMER:

  pCtrl->Timer(wParam);

  return 0;

 ...

 }

 return ::DefWindowProc(hwnd, message, wParam, lParam);

}


void Controller::Timer(int id) {

 _timer.Kill();

 _view.Step();

 UpdateCanvas canvas(_hwnd);

 _view.Update(canvas);

 ::InvalidateRect(_hwnd, 0, FALSE);

 _timer.Set(50);

}


void Controller::Paint() {

 PaintCanvas canvas(_hwnd);

 _view.Paint(canvas);

}

The Update method of View is the workhorse of our program. It creates the image in the buffer. We then call InvalidateRectangle to force the repaint of our window (the last parameter, FALSE, tells Windows not to clear the previous image — we don't want it to flash white before every frame).

Here's the class View, with the three bitmaps.

class View {

public:

 View(HINSTANCE hInst);

 void SetSize(int cxNew, int cyNew) {

  _cx = cxNew;

  _cy = cyNew;

 }

 void Step() { ++_tick; }

 void Update(Canvas& canvas);

 void Paint(Canvas& canvas);

private:

 int _cx, _cy;

 int _tick;

 Bitmap _bitmapBuf; // for double buffering

 Bitmap _background;

 int _widthBkg, _heightBkg;

 Bitmap _sprite;

 Bitmap _mask;

 int _widthSprite, _heightSprite;

};


View::View(HINSTANCE hInst) : _tick (0) {

 // Load bitmap from file

 _background.Load("picture.bmp");

 // Load bitmap from resource

 _background.GetSize(_widthBkg, _heightBkg);

 // Load bitmaps from resources

 _sprite.Load(hInst, IDB_FANNY);

 _mask.Load(hInst, IDB_MASK);

 _sprite.GetSize(_widthSprite, _heightSprite);

 DesktopCanvas canvas;

 _bitmapBuf.CreateCompatible(canvas, 1, 1);

 _cx = 1;

 _cy = 1;

}

Перейти на страницу:

Похожие книги

1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных
C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных