Чтение онлайн

на главную - закладки

Жанры

Применение Windows API

Легалов А. И.

Шрифт:

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.

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.

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.

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);

Поделиться:
Популярные книги

Камень. Книга вторая

Минин Станислав
2. Камень
Фантастика:
фэнтези
8.52
рейтинг книги
Камень. Книга вторая

Эмиссар

Листратов Валерий
8. Ушедший Род
Фантастика:
боевая фантастика
аниме
попаданцы
7.50
рейтинг книги
Эмиссар

На цепи

Уваров
1. На цепи
Старинная литература:
прочая старинная литература
5.00
рейтинг книги
На цепи

Мечник Вернувшийся 1000 лет спустя. Том 2

Ткачев Андрей Юрьевич
2. Вернувшийся мечник
Фантастика:
аниме
фэнтези
попаданцы
5.00
рейтинг книги
Мечник Вернувшийся 1000 лет спустя. Том 2

Эволюционер из трущоб. Том 8

Панарин Антон
8. Эволюционер из трущоб
Фантастика:
попаданцы
аниме
фэнтези
фантастика: прочее
5.00
рейтинг книги
Эволюционер из трущоб. Том 8

Тициан Табидзе: жизнь и поэзия

Табидзе Тициан Юстинович
Документальная литература:
биографии и мемуары
5.00
рейтинг книги
Тициан Табидзе: жизнь и поэзия

Воспоминания о Корнее Чуковском

Коллектив авторов
Документальная литература:
биографии и мемуары
6.25
рейтинг книги
Воспоминания о Корнее Чуковском

Черный Маг Императора 10

Герда Александр
10. Черный маг императора
Фантастика:
юмористическое фэнтези
попаданцы
аниме
сказочная фантастика
фэнтези
5.00
рейтинг книги
Черный Маг Императора 10

Черный Маг Императора 12

Герда Александр
12. Черный маг императора
Фантастика:
юмористическое фэнтези
попаданцы
аниме
сказочная фантастика
фэнтези
5.00
рейтинг книги
Черный Маг Императора 12

Играть... в тебя

Зайцева Мария
3. Звериные повадки Симоновых
Любовные романы:
современные любовные романы
5.25
рейтинг книги
Играть... в тебя

Кодекс Охотника. Книга XXXIII

Винокуров Юрий
33. Кодекс Охотника
Фантастика:
попаданцы
аниме
фэнтези
фантастика: прочее
5.00
рейтинг книги
Кодекс Охотника. Книга XXXIII

Последний Паладин. Том 4

Саваровский Роман
4. Путь Паладина
Фантастика:
фэнтези
попаданцы
аниме
5.00
рейтинг книги
Последний Паладин. Том 4

И в аду есть герои

Панов Вадим Юрьевич
5. Тайный Город
Фантастика:
боевая фантастика
9.19
рейтинг книги
И в аду есть герои

Кодекс Охотника. Книга III

Винокуров Юрий
3. Кодекс Охотника
Фантастика:
фэнтези
попаданцы
аниме
7.00
рейтинг книги
Кодекс Охотника. Книга III