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

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

Жанры

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

Легалов А. И.

Шрифт:

We instruct Windows to release the resources allocated to the bitmap by calling DeleteObject.

class Bitmap {

public:

 Bitmap : _hBitmap (0) {}

 // Transfer semantics

 Bitmap(Bitmap& bmp) : _hBitmap(bmp.Release) {}

 void operator=(Bitmap& bmp) {

if (bmp._hBitmap != _hBitmap) {

Free;

_hBitmap = bmp.Release;

}

 }

 HBITMAP Release {

 HBITMAP h = _hBitmap;

_hBitmap = 0;

return h;

 }

 ~Bitmap {

Free;

 }

 // implicit conversion for use with Windows API

 operator HBITMAP {

return _hBitmap;

 }

protected:

 Bitmap(HBITMAP hBitmap) : _hBitmap(hBitmap) {}

 void Free {

if (_hBitmap) ::DeleteObject(_hBitmap);

 }

 HBITMAP _hBitmap;

};

Now that the management issues are out of the way, we can concentrate on loading bitmaps. The simplest way to include a bitmap in your program is to add it to the resource file. In the resource editor of your development environment you can create new bitmaps or import them from external files. You can either give them names (strings) or numerical ids. When you want to access such a bitmap in your program you have to load it from the resources. Here are two methods that do just that. You have to give them a handle to the program instance.

void Bitmap::Load(HINSTANCE hInst, char const * resName) {

 Free;

 _hBitmap = (HBITMAP)::LoadImage(hInst, resName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

 if (_hBitmap == 0) throw WinException("Cannot load bitmap from resources", resName);

}

void Bitmap::Load(HINSTANCE hInst, int id) {

 Free;

 _hBitmap = (HBITMAP)::LoadImage(hInst, MAKEINTRESOURCE(id), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

 if (_hBitmap == 0) throw WinException("Cannot load bitmap from resources");

}

Loading a bitmap directly from a file is also very simple and can be done using the same API, LoadImage. Remember, it will only work if the file is a Windows (or OS/2) bitmap — such files usually have the extension .bmp. There is no simple way of loading other types of graphics files, .gif, .jpg, .png, etc. You have to know their binary layout and decode them explicitly (there are other web sites that have this information).

void Bitmap::Load(char* path) {

 Free;

 _hBitmap = (HBITMAP)::LoadImage(0, path, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);

 if(_hBitmap == 0) throw WinException("Cannot load bitmap from file", path);

}

Once you got hold of a bitmap, you may want to enquire about its dimensions. Here's how you do it.

void Bitmap::GetSize(int& width, int& height) {

 BITMAP bm;

 ::GetObject(_hBitmap, sizeof(bm), &bm);

 width = bm.bmWidth;

 height = bm.bmHeight;

}

Finally, you might want to create an empty bitmap and fill it with your own drawings programmatically. You have to specify the dimensions of the bitmap and you have to provide a device context (Canvas) for which the bitmap is targeted. Windows will create a different type of bitmap when your target is a monochrome monitor or printer, and different when it's a graphics card set to True Color. Windows will create a bitmap that is compatible with the target device.

Bitmap::Bitmap(Canvas& canvas, int dx, int dy) : _hBitmap (0) {

 CreateCompatible(canvas, dx, dy);

}

void Bitmap::CreateCompatible(Canvas& canvas, int width, int height) {

 Free;

 _hBitmap = ::CreateCompatibleBitmap(canvas, width, height);

}

How do you display the bitmap on screen? You have to blit it. Blit stands for "block bit transfer" or something like that. When you blit a bitmap, you have to specify a lot of parameters, so we'll just encapsulate the blitting request in a separate object, the blitter. This is a very handy object that sets the obvious defaults for blitting, but at the same time lets you override each and any of them.

A blitter transfers a rectangular area of the bitmap into a rectangular area of the screen. The meaning of various parameters is the following:

• Source position: pixel coordinates of the upper left corner of the bitmap area, to be transferred. The default is the upper left corner of the bitmap.

• Destination position: pixel coordinates within the target window of the upper left corner of the transferred area. The default is upper left corner of the window.

• Area dimensions: the dimensions of the rectangular area to be transferred. The default is the dimensions of the bitmap.

• Transfer mode. The way bitmap pixels are combined with existing window pixels. The default, SRCCOPY, copies the pixels over existing pixels. You may also specify more involved logical operations, like SRCAND (Boolean AND), SRCPAINT (Boolean OR), etc. (see your compiler's help on BitBlt).

class Blitter {

public:

 Blitter(Bitmap& bmp) : _bmp (bmp), _mode (SRCCOPY), _xDst (0), _yDst (0), _xSrc (0), _ySrc (0) {

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

Адепт

Листратов Валерий
4. Ушедший Род
Фантастика:
попаданцы
аниме
фэнтези
5.00
рейтинг книги
Адепт

Прайм. Хомори

Бор Жорж
2. Легенда
Фантастика:
боевая фантастика
рпг
5.00
рейтинг книги
Прайм. Хомори

Московское золото или нежная попа комсомолки. Часть Вторая

Хренов Алексей
2. Летчик Леха
Фантастика:
попаданцы
5.00
рейтинг книги
Московское золото или нежная попа комсомолки. Часть Вторая

Чужая семья генерала драконов

Лунёва Мария
6. Генералы драконов
Фантастика:
фэнтези
5.25
рейтинг книги
Чужая семья генерала драконов

Имперец. Том 1 и Том 2

Романов Михаил Яковлевич
1. Имперец
Фантастика:
попаданцы
альтернативная история
аниме
5.00
рейтинг книги
Имперец. Том 1 и Том 2

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

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

Вернувшийся: Первые шаги. Том II

Vector
2. Вернувшийся
Фантастика:
боевая фантастика
космическая фантастика
рпг
5.00
рейтинг книги
Вернувшийся: Первые шаги. Том II

Начало

Харенко Алина Александровна
1. Второй шанс
Фантастика:
фэнтези
5.00
рейтинг книги
Начало

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

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

Ваше Сиятельство 3

Моури Эрли
3. Ваше Сиятельство
Фантастика:
фэнтези
попаданцы
аниме
5.00
рейтинг книги
Ваше Сиятельство 3

Газлайтер. Том 20

Володин Григорий Григорьевич
20. История Телепата
Фантастика:
боевая фантастика
аниме
попаданцы
5.00
рейтинг книги
Газлайтер. Том 20

Хозяин Стужи 7

Петров Максим Николаевич
7. Злой Лед
Фантастика:
аниме
фэнтези
попаданцы
5.00
рейтинг книги
Хозяин Стужи 7

Гримуар темного лорда V

Грехов Тимофей
5. Гримуар темного лорда
Фантастика:
попаданцы
аниме
фэнтези
5.50
рейтинг книги
Гримуар темного лорда V

Ученик. Книга третья

Первухин Андрей Евгеньевич
3. Ученик
Фантастика:
фэнтези
7.64
рейтинг книги
Ученик. Книга третья