Windows API Tutorials
Здесь есть возможность читать онлайн «Windows API Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Windows API Tutorials
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:3 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 60
- 1
- 2
- 3
- 4
- 5
Windows API Tutorials: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Windows API Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Windows API Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Windows API Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
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) {
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 spriteis 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.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Windows API Tutorials»
Представляем Вашему вниманию похожие книги на «Windows API Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Windows API Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.