
- •Теоретичні основи Основні поняття
- •Поняття графічний контекст
- •Визначення dc для об’єктів типу вікно
- •Поняття растру та основні функції роботи з ним.
- •Мал. 3. Приклад малювання ламаної фігури Окрім прямої і точки є функції для малювання готових фігур, як коло(еліпс) прямокутник(квадрат).
- •Створення інструментів.
- •Створення пера
- •Створення щитки
- •Створення об’єкта шрифт
- •Створення регіональних контурів
- •Створення об’єкту типу bitmap (полотно)
Створення інструментів.
Перед тим як здійснювати замітину інструменту в DC, потрібно його створити. Розглянемо функції які для цього використовуються. Розглянемо коротко цей список.
Створення пера
Перо є основним інструментом в GDI. Коли малюємо певне зображення ми можемо намалювати її чорними лініями а потім зафарбувати вміст. Але що робити, коли лінії за тонкі або чорний контур є не доречним? Рішенням є використати інший об’єкт перо.
В основному є 2 функції для створення інструменту перо це CreatePen та CreatePenIndirect.
CreatePen
fnPenStyle // значення яке визначає стиль пера. Може бути комбіноване.
nWidth // ширина пера
crColor // колір (RGB)
Результат: хендл пера
Функція CreatePenIndirect є сестрою близнючкою функції CreatePen з однією різницею, має тільки 1 параметр. Вказівник на структуру LOGPEN, що містить в собі всі поля вище згаданої сестри.
Створення щитки
Малювання контуру зображення це не від’ємна риса зображення, але вміст контору залишається "пустим". Можна методом штрихування зафарбувати вміст контуру, але ця дія сповільняє відтворення зображення. Тому для таких цілей в GDI є об‘єкт щитка. По замовчуванню вона біла. Для створення власної щітки використовується наступні функції.
CreateSolidBrush – створює суцільну щітку на основі певного кольору(RGB).
CreateHatchBrush – створює штриховану щітку на основі певного кольору(RGB).
CreatePatternBrush – створює логічну щітку на основі малюнка
CreateDIBPatternBrush – створює щітку з карти бітів (про це пізніше).
GetSysColorBrush – повертає щітку стандартного(системного) кольору.
CreateBrushIndirect – створення щітки на основі структури LOGBRUSH.
Створення об’єкта шрифт
Найпростішим та най оптимальнішим методом передачі інформації є текст. Для виводу тексту на екран GDI використовує інструмент шрифт. Існує багато функцій роботи з шрифтами, розглядати детально ми їх не будемо, але зупинимося на основній, яка створю простий шрифт.
CreateFont
nHeight, // висота шрифту. Визначається по формулі -MulDiv("Бажана висота", GetDeviceCaps(hDC, LOGPIXELSY), 72);
nWidth, // Висота шрифту
nEscapement, // кут нахилу
nOrientation, // кут базової лінії
fnWeight, // товщина шрифту (0..900) кратне 100. Диф. Хелп.
fdwItalic, // текст буде курсивом ( "0" або "1" )
fdwUnderline, // текст буде підкреслений ( "0" або "1" )
fdwStrikeOut, // текст буде закреслений ( "0" або "1" )
fdwCharSet, // задати набір символів
fdwOutputPrecision, // задати точність виводу літер (одна із констант)
fdwClipPrecision, // задає точність відсічення по границям літер (одна із констант)
fdwQuality, // задає якість виводу даних
fdwPitchAndFamily, // встановлює крок між символами
lpszFace // вказівник на рядок що містить назву шрифта зареєстрованого у системі
Результат: хендл нового шрифта
Приклад створення простого шрифта.
.data
szfont db 'Arial',0
.code
…..
invoke GetDeviceCaps,hdc1,LOGPIXELSY
invoke MulDiv,40,eax,72
neg eax ; -eax
invoke CreateFont,eax,40,0,0,FW_NORMAL,1,0,0,DEFAULT_CHARSET,\
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,\
DEFAULT_PITCH,addr szfont
……
Також перегляньте наступні функції:
Функції |
Опис |
AddFontMemResourceEx |
Добавляє у систему новий шрифт з області пам‘яті |
AddFontResource |
Добавляє у систему новий шрифт |
AddFontResourceEx |
Добавляє у систему новий шрифт (з розширеними можливостями) |
CreateFont |
Ств. шрифт |
CreateFontIndirect |
Ств. шрифт за допомогою структури LOGFONT |
CreateFontIndirectEx |
Ств. шрифт за допомогою структури LOGFONT (розширене) |
CreateScalableFontResource |
Creates a font resource file for a scalable font. |
DrawText |
Draws formatted text in a rectangle. |
DrawTextEx |
Draws formatted text in rectangle. |
EnumFontFamExProc |
An application defined–callback function used with EnumFontFamiliesEx to process fonts. |
EnumFontFamiliesEx |
Enumerates all fonts in the system with certain characteristics. |
ExtTextOut |
Draws a character string. |
GetAspectRatioFilterEx |
Gets the setting for the aspect-ratio filter. |
GetCharABCWidths |
Gets the widths of consecutive characters from the TrueType font. |
GetCharABCWidthsFloat |
Gets the widths of consecutive characters from the current font. |
GetCharABCWidthsI |
Gets the widths of consecutive glyph indices or from an array of glyph indices from the TrueType font. |
GetCharacterPlacement |
Gets information about a character string. |
GetCharWidth32 |
Gets the widths of consecutive characters from the current font. |
GetCharWidthFloat |
Gets the fractional widths of consecutive characters from the current font. |
GetCharWidthI |
Gets the widths of consecutive glyph indices or an array of glyph indices from the current font. |
GetFontData |
Gets metric data for a TrueType font. |
GetFontLanguageInfo |
Returns information about the selected font for a display context. |
GetFontUnicodeRanges |
Tells which Unicode characters are supported by a font. |
GetGlyphIndices |
Translates a string into an array of glyph indices. |
GetGlyphOutline |
Gets the outline or bitmap for a character in the TrueType font. |
GetKerningPairs |
Gets the character-kerning pairs for a font. |
GetOutlineTextMetrics |
Gets text metrics for TrueType fonts. |
GetRasterizerCaps |
Tells whether TrueType fonts are installed. |
GetTabbedTextExtent |
Computes the width and height of a character string, including tabs. |
GetTextAlign |
Gets the text-alignment setting for a device context. |
GetTextCharacterExtra |
Gets the current intercharacter spacing for a device context. |
GetTextColor |
Gets the text color for a device context. |
GetTextExtentExPoint |
Gets the number of characters in a string that will fit within a space. |
GetTextExtentExPointI |
Gets the number of glyph indices that will fit within a space. |
GetTextExtentPoint32 |
Computes the width and height of a string of text. |
GetTextExtentPointI |
Computes the width and height of an array of glyph indices. |
GetTextFace |
Gets the name of the font that is selected into a device context. |
GetTextMetrics |
Fills a buffer with the metrics for a font. |
PolyTextOut |
Draws several strings using the font and text colors in a device context. |
RemoveFontMemResourceEx |
Removes a font whose source was embedded in a document from the system font table. |
RemoveFontResource |
Removes the fonts in a file from the system font table. |
RemoveFontResourceEx |
Removes a private or non-enumerable font from the system font table. |
SetMapperFlags |
Alters the algorithm used to map logical fonts to physical fonts. |
SetTextAlign |
Sets the text-alignment flags for a device context. |
SetTextCharacterExtra |
Sets the intercharacter spacing. |
SetTextColor |
Sets the text color for a device context. |
SetTextJustification |
Specifies the amount of space the system should add to the break characters in a string. |
TabbedTextOut |
Writes a character string at a location, expanding tabs to specified values. |
TextOut |
Writes a character string at a location. |
Нижче приведений код програми для завантаження власних шрифтів
.date
szPathFont db 'Cheese and Mouse.ttf',0
szfont db 'Cheese and Mouse',0
szTest db 'Hello',0
size_szTest dd $-szTest ; визначити довжину стрічки ($ = поточна адреса змінної)
.code
…..
DlgProc proc hWin:HWND,uMsg:UINT,wParam:WPARAM,lParam:LPARAM
mov eax,uMsg
.if eax==WM_INITDIALOG
invoke GetDC,hWin
mov hdc1,eax
.elseif eax==WM_COMMAND
.if wParam == 1001 ;натискаємо кнопку
invoke AddFontResource,addr szPathFont ; додаємо новий шрифт в систему
invoke GetDeviceCaps,hdc1,LOGPIXELSY
invoke MulDiv,60,eax,72
neg eax ; -eax
invoke CreateFont,eax,60,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET, \
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,\
DEFAULT_QUALITY,DEFAULT_PITCH,addr szfont
invoke SelectObject,hdc1,eax ; підміняємо в DC новий шрифт
invoke SetTextColor,hdc1,0ffh ; коліт тексту червоний
invoke SetBkMode,hdc1,TRANSPARENT ; фон тексту прозорий
invoke TextOut,hdc1,50,100,addr szTest,size_szTest ; виводимо текст
invoke RemoveFontResource,addr szPathFont ; видаляємо встановлений шрифт
.endif
.elseif eax==WM_CLOSE
invoke ReleaseDC,hWin,hdc1
invoke EndDialog,hWin,0
.else
mov eax,FALSE
ret
.endif
mov eax,TRUE
ret
DlgProc endp
…………
Мал. 4. Приклад завантаження власного шрифту