Библиотека knigago >> Компьютеры: Разработка ПО >> Программирование: прочее >> Применение Windows API


СЛУЧАЙНЫЙ КОММЕНТАРИЙ

# 613, книга: Мистическая сага
автор: Зинаида Порох

Уважаемые админы. Я автор - Зинаида Порох. В настоящее время я сняла Мистическую сагу со всех площадок. Эта книга написана между делом, второпях - в ней много ошибок и нестыковок. Сейчас я её основательно редактирую. Просьба к Вам - снимите, пожалуйста, Мистическую сагу с Вашего сайта. Временно. Скоро я снова выложу её в новом и подработанном варианте. Заранее благодарю Вас.

СЛУЧАЙНАЯ КНИГА

ЛеХИ. Борцы за свободу Израиля. Эмануэль Кац
- ЛеХИ. Борцы за свободу Израиля

Жанр: История: прочее

Год издания: 1980

Серия: Библиотечка сиониста

А И Легалов - Применение Windows API

Применение Windows API
Книга - Применение Windows API.  А И Легалов  - прочитать полностью в библиотеке КнигаГо
Название:
Применение Windows API
А И Легалов

Жанр:

Современные российские издания, Литература ХXI века (эпоха Глобализации экономики), Windows, Программирование: прочее, Windows API

Изадано в серии:

неизвестно

Издательство:

неизвестно

Год издания:

ISBN:

неизвестно

Отзывы:

Комментировать

Рейтинг:

Поделись книгой с друзьями!

Помощь сайту: донат на оплату сервера

Краткое содержание книги "Применение Windows API"

Аннотация к этой книге отсутствует.

Читаем онлайн "Применение Windows API". [Страница - 31]

_bmp (bmp), _mode (SRCCOPY), _xDst (0), _yDst (0), _xSrc (0), _ySrc (0) {

  bmp.GetSize(_width, _height);

 }

 void SetMode(DWORD mode) {

  _mode = mode;

 }

 void SetDest(int x, int y) {

  _xDst = x;

  _yDst = y;

 }

 void SetSrc(int x, int y) {

  _xSrc = x;

  _ySrc = y;

 }

 void SetArea(int width, int height) {

  _width = width;

  _height = height;

 }

 // transfer bitmap to canvas

 void BlitTo(Canvas & canvas);

private:

 Bitmap& _bmp;

 int _xDst, _yDst;

 int _xSrc, _ySrc;

 int _width, _height;

 DWORD _mode;

};

The BlitTo method performs the transfer from the bitmap to the window (or printer) as described by its Canvas.

void Blitter::BlitTo(Canvas& canvas) {

 // Create canvas in memory using target canvas as template

 MemCanvas memCanvas (canvas);

 // Convert bitmap to the format appropriate for this canvas

 memCanvas.SelectObject(_bmp);

 // Transfer bitmap from memory canvas to target canvas

 ::BitBlt(canvas, _xDst, _yDst, _width, _height, memCanvas, _xSrc, _ySrc, _mode);

}

The API, BitBlt, transfers bits from one device to another. That's why we have to set up a fake source device. This "memory canvas" is based on the actual canvas--in this case we use target canvas as a template. So, for instance, if the target canvas describes a True Color device, our MemCanvas will also behave like a True Color device. In particular, when our bitmap is selected into it, it will be converted to True Color, even if initially it was a monochrome or a 256-color bitmap.

The simplest program that loads and displays a bitmap might look something like this: There is a View object that contains a bitmap (I assume that the file "picture.bmp" is located in the current directory). It blits it to screen in the Paint method.

class View {

public:

 View() {

  _background.Load("picture.bmp");

 }

 void Paint(Canvas& canvas) {

  Blitter blitter(_background);

  blitter.BlitTo(canvas);

 }

private:

 Bitmap _background;

};

A sprite is an animated bitmap that moves over some background. We already know how to display bitmaps — we could blit the background first and then blit the sprite bitmap over it. This will work as long as the sprite is rectangular. If you want to be more sophisticated and use a non-rectangular sprite, you need a mask.

The two pictures below are that of a sprite (my personal pug, Fanny) and its mask. The mask is a monochrome bitmap that has black areas where we want the sprite to be transparent. The sprite, on the other hand, must be white in these areas. What we want is to be able to see the background through these areas.

Книгаго: Применение Windows API. Иллюстрация № 6
Книгаго: Применение Windows API. Иллюстрация № 7 The trick is to first blit the background, then blit the mask using logical OR, and then blit the sprite over it using logical AND.

ORing a black mask pixel (all zero bits) with a background pixel will give back the background pixel. ORing a white mask pixel (all one bits) with a background will give a white pixel. So after blitting the mask, we'll have a white ghost in the shape of our sprite floating over the background.

Книгаго: Применение Windows API. Иллюстрация № 8 ANDing a white sprite pixel (all ones) with a background pixel will give back the background pixel. ANDing a non-white sprite pixel with the white (all ones) background (the ghost from previous step) will give the sprite pixel. We'll end up with the sprite superimposed on the background.

Книгаго: Применение Windows API. Иллюстрация № 9 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<Controller*>(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);

--">

Оставить комментарий:


Ваш e-mail является приватным и не будет опубликован в комментарии.