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

  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:

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

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

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

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

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

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