SlideShare a Scribd company logo
Programirajmo grafiku
uz stari, dobri BGI...
Knjiga I.: BGI & CodeBlocks
U ovom priručniku autor je prikupio s raznih strana na
internetu vrijednu kolekciju materijala o oživljavanju
Borland Graphics Interface-a u Code::Blocks-u, modernom
sučelju za programiranje u C i C++ jezicima. Dani su i
konkretni primjeri elementarne grafike za školske potrebe.
Jadranko Tudović (2010)
ISI - Prva srednja informatička škola sp.j.
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 2
ISI-Prvasrednjainformatičkaškolasp.j.
SADRŽAJ:
PREDGOVOR........................................................................................................................................ 5
OSNOVE RAČUNALNE GRAFIKE........................................................................................................... 6
ALATI ZA PROGRAMIRANJE u C jeziku................................................................................................. 6
Instalacija grafičke biblioteke u Code::Blocks ..................................................................................... 9
Bug u BGIgraphics.h (tj. winbgim.h).................................................................................................. 10
Što još treba ispraviti?....................................................................................................................... 11
Kako koristiti biblioteku libbgix.a? .................................................................................................... 11
Moj prvi program s grafikom............................................................................................................. 12
PROBLEMI?........................................................................................................................................ 13
Pregled češće korištenih naredbi BGI grafike................................................................................... 14
Primjeri programiranja grafike.......................................................................................................... 16
BGI_PRIMJER_01: Crtanje linije................................................................................................. 16
BGI_PRIMJER_02: Crtanje kvadrata .......................................................................................... 16
BGI_PRIMJER_03: Crtanje kružnice žute boje........................................................................... 16
BGI_PRIMJER_04: Crtanje ELIPSE žute boje .............................................................................. 16
BGI_PRIMJER_04: Crtanje TROKUTA žute boje......................................................................... 17
Biblioteka rutina za programiranje miša........................................................................................... 18
Funkcije za programiranje miša..................................................................................................... 19
Primjer programiranja miša s ismouseclick i getmouseclick funkcijama..................... 20
Primjer rutine za miša s rukovateljem (eng. mouse handler) ....................................................... 20
PRIMJER: Unos koordinata poligona mišem ............................................................................. 21
Grafičke rutine u BGI biblioteci ......................................................................................................... 22
Inicijalizacija grafike:...................................................................................................................... 22
BOJE u Winbgim ............................................................................................................................ 22
RGB boje........................................................................................................................................ 22
Upravljanje ulaza preko TIPKOVNICE ................................................................................................ 23
Napredne grafičke naredbe u BGI biblioteci ..................................................................................... 23
Podrška za dvostruko baferiranje (Double-Buffering)................................................................... 23
Podrška za ispis na grafički prozor................................................................................................. 23
Podrška za štampanje, učitavanje i zapisivanje grafike................................................................. 23
Podrška za višestruke prozore....................................................................................................... 24
Ostala dokumentacija za proučavanje BGI grafike........................................................................ 24
Kako ukloniti konzolni (tzv. DOS) prozor? .................................................................................... 24
Borland Graphics Interface (BGI) for Windows................................................................................. 25
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 3
ISI-Prvasrednjainformatičkaškolasp.j.
FUNKCIJE: ...................................................................................................................................... 25
Koje su to naredbe u winbgim.h?.................................................................................................. 27
CRTAJUĆE funkcije (eng. Drawing Functions)............................................................................ 27
RAZNE funkcije (eng. Miscellaneous Functions) ....................................................................... 27
"PROZORSKE" funkcije (eng. Window Creation / Graphics Manipulation)............................... 28
Interakcija s korisnikom (eng. User Interaction) ....................................................................... 28
User-Controlled Window Functions (winbgi.cpp) ..................................................................... 28
Double buffering support (winbgi.cpp)..................................................................................... 28
"SLIKOVNE" funkcije (rasterska grafika) (eng. Image Functions (drawing.cpp))....................... 29
TEKSTNE iliti "PISAJUĆE" funkcije (eng. Text Functions (text.cpp))........................................... 29
"MIŠJE" funkcije (eng. Mouse Functions (mouse.cpp))............................................................. 29
Upravljanje paletama boja (eng. Palette Functions)................................................................. 29
FUNKCIJE, još jednom.................................................................................................................... 30
Drawing Functions..................................................................................................................... 30
Miscellaneous Functions ........................................................................................................... 30
Window Creation / Graphics Manipulation .............................................................................. 31
User Interaction......................................................................................................................... 31
User-Controlled Window Functions (winbgi.cpp) ..................................................................... 31
Double buffering support (winbgi.cpp)..................................................................................... 31
Image Functions (drawing.cpp)................................................................................................. 31
Text Functions (text.cpp)........................................................................................................... 32
Mouse Functions (mouse.cpp).................................................................................................. 32
Palette Functions....................................................................................................................... 32
Color Macros ............................................................................................................................. 32
Napredno korištenje BGI grafike....................................................................................................... 33
initwindow..................................................................................................................................... 33
setcurrentwindow ......................................................................................................................... 34
getcurrentwindow......................................................................................................................... 34
closegraph ..................................................................................................................................... 35
swapbuffers................................................................................................................................... 36
getactivepage ................................................................................................................................ 36
getvisualpage................................................................................................................................. 37
setactivepage................................................................................................................................. 37
setvisualpage................................................................................................................................. 38
setviewport.................................................................................................................................... 39
clearviewport................................................................................................................................. 40
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 4
ISI-Prvasrednjainformatičkaškolasp.j.
getx................................................................................................................................................ 41
gety................................................................................................................................................ 42
moveto .......................................................................................................................................... 43
moverel.......................................................................................................................................... 44
getmaxx ......................................................................................................................................... 45
getwindowwidth............................................................................................................................ 46
getwindowheight........................................................................................................................... 46
setcolor.......................................................................................................................................... 47
setbkcolor...................................................................................................................................... 49
getch.............................................................................................................................................. 50
kbhit............................................................................................................................................... 52
KONSTANTIN KNIZNIK ....................................................................................................................... 54
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 5
ISI-Prvasrednjainformatičkaškolasp.j.
PREDGOVOR
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 6
ISI-Prvasrednjainformatičkaškolasp.j.
OSNOVE RAČUNALNE GRAFIKE
Uporaba računala uz primjenu grafike daje korisniku puno više informacija od pukog računanja brojki
i premetanja slova. Međutim, grafika u računalima klase "IBM-PC" – koja su građena na principima
otvorene hardverske arhitekture (što pak znači da korisnik može imati bilo kakav grafički podsustav u
svom računalu) rezultirala je otežanim pristupom grafičkim resursima računala.
Naime, grafičkim mogućnostima računala upravlja operacijski sustav računala (skraćeno OS). Svi
zahtijevi za grafikom idu strogo preko "njega" (> OS-a). Stoga, da bi naše programiranje računala uz
primjenu grafike uopće "prošlo" – jednostavno moramo dodati biblioteke (eng. library) s novim,
grafičkim naredbama (najčešće funkcijama) . Tek tada će biti moguće na jednostavan način otvarati
grafički prozor u kojega se može usmjeriti izlaz iz našeg programa. Recimo samo i ovu zanimljivu
činjenicu – pisanje slova u grafičkom prozoru postaje crtanje slova, jer tu više ne prolaze iste naredbe
kao u konzolnom (onom tekstualnom) prozoru.
Dobar link o Dev-C++ & Graphics http://www.onecore.net/dev-c-graphics.htm
Što je WinBGIm
- WinBGIm is a basic graphics drawing package that emulates one of the most successful graphics
libraries of all times, the Borland Graphics Interface (BGI). WinBGIm adds some extra facilities, like the
possibility of catching mouse clicks and mouse position.
The success of BGI was due to its simplicity. The code of graphical programs produced with WinBGIm is
very simple, compared to that of other graphics packages.
ALATI ZA PROGRAMIRANJE u C jeziku
Programiranje računala je vještina koja se obavlja uz uporabu određenih programskih alata. Ako
gledamo po dijelovima priču o programiranju – tada bi mogli zaključiti da nam je glavni alat neki
prevodilac ili u žargonu kompajler (od eng. compiler), pa zatim neki editor teksta (u Windows okolini
u najmanju ruku spartanski Notepad.exe, no šalu na stranu – puno bolje: Notepad++), pa zatim neki
program koji će povezati datoteke... dakle linker.exe itd....
Na raspolaganju imamo razne kompajlere:
 MinGW 2.95/3.x/4.x/5.0
 Cygwin
 Borland C++ Compiler
 Microsoft C++ Compiler
 Intel C++ Compiler
 Lcc-Win32
 Open Watcom C/C++
 Digital Mars C/C++
 Ch Interpreter
 Pelles C
Sve to puno bolje od pojedinih dijelova iz gornje priče nalazi se u cjelovitim, objedinjenim ili
integriranim sustavima – skraćenica na engleskom jeziku za takve sustave je IDE.
IDE dolazi od Integrated Development Environment, dakle integrirana razvojna okolina ili sučelje
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 7
ISI-Prvasrednjainformatičkaškolasp.j.
Za potrebe programiranja u C odnosno C/C++ jeziku imamo na raspolaganju desetine sustava. Evo
nekoliko njih koji mi padaju na pamet:
NAZIV Licenca Win Lin Mac Specifično NAPOMENA
1 BloodShed Dev-
C++
GPL zadnja verzija: 02-2005! Više se ne
održava!
2 CodeLite GPL
3 Code::Blocks GPL
4 Pelles C Free Windows
CE
Pravi, "čistokrvni" C prevodilac i
razvojna okolina. Redovito održavan.
Najnoviji C standardi (C11)!!!
5 C-Free Comerc.
6 NetBeans Free
7 Eclipse Free
8 Visual C++ 2010
Express Edition
Free
9 KDevelop GPL
*ima ih puno više...
Code::Blocks
Code::Blocks je besplatno C/C++ integrirano razvojno sučelje, IDE, napravljeno po najvišim
zahtjevima korisnika. Dizajnirano je kao potpuno proširiva i prilagodljiva (konfigurabilna) radna
okolina za potrebe programiranja.
Kompajleri koje trenutno podržava Code::Blocks:
 GNU GCC (incl. G77) (Linux)
 MinGW GCC (incl. G77) (Win32)
 MSP430 GCC (Win32, Linux, BSD)
 TriCore GCC (Win32, Linux)
 PowerPC GCC (Win32, Linux)
 Apple GCC (Xcode) (Mac OS X)
 Microsoft Visual C++ Toolkit 2003 (Win32)
 Microsoft Visual C++ 2005 (Win32)
 LCC (Win32)
 Borland's C++ Compiler 5.5 (Win32)
 DigitalMars C/C++ (Win32)
 OpenWatcom (Win32)
 Intel C++ compiler (Win32)
 Small Device C Compiler (SDCC)
 Digital Mars D
 GDC D Compiler
 LLVM D Compiler
*prema: http://wiki.codeblocks.org/index.php?title=Main_Page
Borland BGI Graphics
Zahvaljujući vrijednom radu ruskog matematičara i računalnog znastvenika Konstantina Knizhnika,
kao i Marku Richardsonu i Michaelu Mainu iz Sveučilišta Coloradu (University of Colorado), te
zadnjim modifikacijama Adriana Sandora (modifications by Adrian Sandor) raspolažemo s četiri
fantastične datoteke koje nam omogućuju uporabu grafičkih naredaba koje je izvorno tvrtka Borland
uključila u njihovo klasično integrirano sučelje za razvoj Turbo C++ aplikacija.
To su sljedeća četiri fajla, komprimirana u winbgim_devcpp4990_20041220.zip:
1. winbgim.h (kopirati u C:Program FilesCodeBlocksMinGWinclude)
2. conio.h (kopirati u C:Program FilesCodeBlocksMinGWinclude)
3. libbgi.a (kopirati u C:Program FilesCodeBlocksMinGWlib)
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 8
ISI-Prvasrednjainformatičkaškolasp.j.
4. libconio.a (kopirati u C:Program FilesCodeBlocksMinGWlib)
VAŽNA NAPOMENA: Pretraživanjem interneta naći ćete više izvora za skidanje navedenih datoteka.
Međutim, one nisu iste po mogućnostima. Nakon testiranja više njih odlučio sam se za download sa
stranice: http://www.uniqueness-template.com/devcpp. Istina sve je navedeno za uporabu u Dev-C++
razvojnoj okolini, što ovog trena slobodno zanemarite!
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 9
ISI-Prvasrednjainformatičkaškolasp.j.
Slika 1 - izbornik Settings
Slika 2 – Linker settings
Instalacija grafičke biblioteke u Code::Blocks
U programsku razvojnu okolinu Code::Blocks jednostavnu 2D grafiku, razvijenu pred 25 godina u
Borlandu, jednoj od najpoznatijih softverskih tvrtki, uključujemo na sljedeći način:
0. korak: napraviti download 2 datoteke s adrese:
PROMIJENITI OVAJ DIO – staviti fajlove na naš server/portal na eng. i hrv. te komentirati
 http://www.uniqueness-template.com/devcpp/graphics.h
 http://www.uniqueness-template.com/devcpp/libbgi.a
1. korak: u folder include kopirati datoteku: BGIgraphics.h
2. korak: u folder lib kopirati datoteku: libbgix.
3. korak: Nakon toga potrebno je prijaviti korištenje navedene biblioteke spuštanjem izbornika
Settings ->Compiler and debugger otvorimo karticu (tab) Linker utipkamo u Other linker
settings: -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 10
ISI-Prvasrednjainformatičkaškolasp.j.
Bug u BGIgraphics.h (tj. winbgim.h)
Upavo smo otkrili čudnovati bug u header-fajlu BGIgraphics.h (izvorno: winbgim.h). Sasvim slučajno,
ustanovljavajući zašto BGI grafika radi na mom računalu dok isti krajnje jednostavni primjer ne želi
proraditi – dapače, uporno javlja grešku koju sam stalno ignorirao dok nisam shvatio da je to istinita
poruka od kompajlera...
Nekim čudom, meni je implementacija BGI grafike proradila glatko na Code::Blocks-u. Prvobitno sam
imao Code::Blocks 8.6 (ili tako nekako) i nedavno sam ga "zgazio" verzijom 10.5. Istina, javljao je neke
poruke koje sam zanemario. Glavno mi je bilo da stvar radi! Dapače, radila je i BGI grafika po logici
ugradnje u Dev-C++ (stavi winbgim.h u include-folder i lbgi.a u lib-folder i pazi ovo, sve što radiš,
započni kao C++ a ne kao C projekt!!!). Sve mi je radilo.
Onda sam odlučio sve to instalirati na školska računala. Super. Skinuli smo MingW varijantu, ugradili
moju varijantu BGI fajlova (moju samo po preimenavanju, jer ništa nisam prekodirao) – i idemo
testirati. Program za test je krajnje jednostavan:
#include <BGIgraphics.h>
int main()
{
int x1,y1,x2,y2,x3,y3;
//otvori graficki prozor velicine 400x300 pixela
initwindow(400,300,"Crtamo TROKUT");
x1=200; y1=50;
x2=120; y2=190;
x3=280; y3=210;
line(x1,y1,x2,y2);
line(x2,y2,x3,y3);
line(x3,y3,x1,y1);
getch();
closegraph();
}
Međutim, neće raditi!!! Uporno javlja grešku:
...i stvarno, u header-fajlu BGIgraphics.h potkrala se greška na liniji 302. Ta greška zasmetala je tek
novoj verziji MingW kompajlera! Stoga sam tu grešku ispravio i sada sve radi!
Naime na liniji 302 u BGIgraphics.h (bivše ime: winbgim.h) pogrešno je dva puta uzastopce navedena
integerska varijabla right. U drugom navodu int right promijenjen je u int top =... i tako je ispravljena
ova greška.
void printimage(
const char* title=NULL,
double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75,
int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX,
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 11
ISI-Prvasrednjainformatičkaškolasp.j.
bool active=true, HWND hwnd=NULL
);
Što još treba ispraviti?
Detalj koji nervira ali definitivno nije bug je problem sa utipkavanjem desne uglate zagrade ("]") u CB-
u. Tu pak treba promijeniti postavku koja je prilično duboko skrivena u opciji Settings :
Settings-> Editor -> Keyword Shortcuts -> Search -> Go to function -> u desnom prozoru tekst: Ctrl
Shift G ili zamijeniti ili obrisati.
Kako koristiti biblioteku libbgix.a?
Programska biblioteka libbgix.a je tzv. objektna datoteka koja sadrži binarni zapis kompiliranih
naredbi za rad s elementarnom grafikom. Popis tih naredbi je vidljiv iz header datoteke BGIgraphics.h
koja "inkludira" sve te grafičke naredbe. Iz praktičnih razloga ali i zbrke na internetu odlučio sam
preimeovati te dvije datoteke:
winbgim.h BGIgraphics.h
libbgi.a libbgix.a
Glavni razlog je to što na internetu postoje tri-četiri verzije koje nisu iste. Nakon što sam to istražio
odabrao sam najbolju verziju i dao joj novo ime.
Dobro je znati da biblioteka BGIgraphics.h automatski uključuje sljedeće tri biblioteke:
#include <stddef.h>
#include <conio.h>
#include <windows.h>
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 12
ISI-Prvasrednjainformatičkaškolasp.j.
Moj prvi program s grafikom...
Nakon pokretanja Code::Bocks-a, započnimo ovaj zadatakakreiranjem nove datoteke na sljedeći
način:
csN(to je: File > New > Empty File)
Zatim utipkajmo sljedeći programski tekst u editor:
... i pohranimo ga naredbom Save As u odabranu mapu uz obavezno pisanje ekstenzije datoteke kao
.cpp !!!
Još jednom: OBAVEZNO NAPISATI .cpp inače ništa od grafike!!!
Tipkom 9 pokrenemo Build & Run i dobijemo grafički prozor veličine 400x300 piksela u čijem
središtu je nacrtana kružnica radijusa 50 piksela, žute boje!!!
Probajte!!!
#include <BGIgraphics.h>
int x=400, y=300; //deklaracija varijabli za širinu i visinu garfičkog prozora
int main()
{
initwindow(x,y,"Kruznica..."); //otvori grafički prozor veličine 400 X 300 piksela
setcolor (14); // postavimo boju = 14 --> žuta!
circle(x/2,y/2,50); // crtaj kružnicu u središtu prozora radiusa 50 piksela
while(!kbhit()); //čekaj dok korisnik ne pritisne bilo koju tipku na tipkovnici
closegraph(); //zatvori grafički prozor
return 0;
}
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 13
ISI-Prvasrednjainformatičkaškolasp.j.
PROBLEMI?
....Ali ja sam dobio sljedeće greške nakon pritiska na tipku F9:
Ništa zato, to samo znači da nisi odradio korak br. 3.
Sretno! i uz puno strpljenja!!!
Vaš profesor, Jadranko Tudović
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 14
ISI-Prvasrednjainformatičkaškolasp.j.
Pregled češće korištenih naredbi BGI grafike
Radnja Sintaksa objašnjenje
otvaranje
grafičkog
prozora
initwindow (wx,wy) ili
initwindow (wx,wy,"NASLOV")ili
initwindow (wx,wy,"nas",xo,yo)
otvara grafički prozor širine wx piksela i
visine wy piksela, a ako se navedu xo i yo
koordinate – tada je to početak gronjeg
lijevog ugla prozora dok je "Naslov" naziv
grafičkog prozora.
zatvaranje
grafičkg
prozora
closegraph();
uvijek zadnja naredba u slijedu izvršavanja
grafičkih naredbi.NAPOMENA – prije toga
aktivirati npr. getch();
brisanje
grafičkog
prozora
cleardevice();
briše sve nacrtano na postojećem
grafičkom prozoru (tako da graf. prozor
ispuni bojom podloge) i postavlja kursor na
"home position" – 0,0.
Pomak
pozicije
crtanja
(bez traga)
moveto(x,y);
pomiče pokazivač u točku s koordinatama
(x,y)
moverel(dx,dy);
pomiče pokazivač za dx u smjeru osi x i za
dy u smjeru osi y
crtanje
točke
putpixel(x,y,boja); crta točku s koordinatama (x,y) zadane boje
getx(); vraća poziciju koordinate x
gety(); vraća poziciju koordinate y
crtanje
linija
line (x1,y1,x2,y2);
Povlači liniju od točke (x1,y1) do točke
(x2,y2)
linerel(dx,dy);
Crta liniju od trenutnog položaja pokazivača
do točke koja je za dx udaljena po x-osi, a
za dy po y-osi
lineto (x,y);
Crta liniju od trenutnog položaja pokazivača
do točke s koordinatama (x,y)
setlinestyle(x,1,1);
stil linije (0-puna crta, 1-točkasta, 2-
iscrtkana, 3-deblja točkasta, 4-točkasta s
većim razmakom, 5-debela crta
boja podloge setbkcolor(x); određuje boju podloge prozora (0 -15)
boja linije ili
teksta
setcolor(x); određuje boju linija (0 -15)
pravokutnik
i
kvadar
rectangle(x1,y1,x2,y2);
Pravokutnik kojemu su (x1,y1) koordinate
gornjeg lijevog, a (x2,y2) donjeg desnog
vrha
bar(x1,y1,x2,y2);
Pravokutnik ispunjen trenutnom bojom i
trenutnim stilom
bar3d(x1,y1,x2,y2,dubina,oznaka);
Trodimenzionalni pravokutnik (kvadar).
Dubinom određujemo trodimenzionalnost.
Za najbolji dojam trodimenzionalnosti
preporučuje se uzeti 25% širine
pravokutnika (x2-x1)/4. Posljednja oznaka
određuje da li je lik zatvoren (1) ili otvoren
(0)
kružnica circle(x,y,r);
kružnica polumjera r sa središtem u točki
(x,y)
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 15
ISI-Prvasrednjainformatičkaškolasp.j.
kružni luk arc(x,y,pocetak,kraj,r);
dio kružnice sa središtem u točki (x,y)
polumjera r od mjesta pocetak (u
stupnjevima) do mjesta kraj
isječak pieslice(x,y,pocetak,kraj,r);
popunjen dio kruga od mjesta pocetak do
mjesta kraj
elipsa
ellipse(x,y,pocetak,kraj,a,b);
elipsa sa središtem u točki(x,y) od mjesta
početak (u stupnjevima) do mjesta kraj,
duljine velike osi a, a male osi b
fillellipse(x,y,a,b) popunjena elipsa
sector(x,y,pocetak,kraj,a,b); popunjen dio elipse
ispis teksta
outtext(string);
ispisuje tekst u grafičkom prozoru počevši
od vrha prozora
outtextxy(x,y,string);
ispisuje tekstualni string s početkom na
koordinati x,y
settextstyle(oblik,smjer,vel);
postavke stila teksta:
int oblik, vrijednosti: 0 do 10
int smjer, vrijednosti 0 do 2 gdje je
HORIZ_DIR = 0
VERT_DIR = 1
-VERT_DIR = 2
int vel, veličina slova (0,1,2,3...)
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 16
ISI-Prvasrednjainformatičkaškolasp.j.
Primjeri programiranja grafike
BGI_PRIMJER_01: Crtanje linije
//BGI_PRIMJER_01: Crtanje linije
#include <BGIgraphics.h>
int main()
{
initwindow(400,300); //otvaranje grafičkog prozora 400x300 pixela
moveto(0,0); //pozicioniraj pero na 0,0 (gornji lijevi ugao)
lineto(50,50); //povuci liniju do točke 50,50
while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku
//tipku
closegraph(); //zatvori grafički prozor
return 0;
}
BGI_PRIMJER_02: Crtanje kvadrata
//BGI_PRIMJER_02: Crtanje kvadrata
#include <BGIgraphics.h>
int main()
{
initwindow(400,300); //otvaranje grafičkog prozora 400x300 pixela
moveto(20,20);
lineto(20,50);
lineto(50,50);
lineto(50,20);
lineto(20,20);
while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku
//tipku
closegraph(); //zatvori grafički prozor
return 0;
}
BGI_PRIMJER_03: Crtanje kružnice žute boje
//BGI_PRIMJER_03: Crtanje kružnice žute boje
#include <BGIgraphics.h>
int main()
{
initwindow(400,400); //otvaranje grafičkog prozora 400x400 pixela
setcolor(14); //postavi boju pera na 14 (=žuto)
circle(200,200,50); //kružnica radiusa 50 na koord. 200,200
while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku
//tipku
closegraph(); //zatvori grafički prozor
return 0;
}
BGI_PRIMJER_04: Crtanje ELIPSE žute boje
//BGI_PRIMJER_04: Crtanje ELIPSE žute boje
#include <BGIgraphics.h>
int main()
{
initwindow(400,400); //otvaranje grafičkog prozora 400x400 pixela
setcolor(14); //postavi boju pera na 14 (=žuto)
int xo = 200; //x-koord. središta elipse
int yo = 200; //y-koord. središta elipse
int fip= 0; //početni kut fi
inf fik= 360; //krajnji kut fi
int rx = 100; //radius po x osi
int ry = 50; //radius po y osi
ellipse(xo,yo,fip,fik,rx,ry);
while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku
//tipku
closegraph(); //zatvori grafički prozor
return 0;
}
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 17
ISI-Prvasrednjainformatičkaškolasp.j.
BGI_PRIMJER_04: Crtanje TROKUTA žute boje
//BGI_PRIMJER_04: Crtanje TROKUTA žute boje
#include <BGIgraphics.h>
int main()
{
int x1,y1,x2,y2,x3,y3;
//otvori grafički prozora 400x300 pixela s nazivom "Crtamo TROKUT"
initwindow(400,300,"Crtamo TROKUT");
x1=200; y1=50;
x2=120; y2=190;
x3=280; y3=210;
line(x1,y1,x2,y2);
line(x2,y2,x3,y3);
line(x3,y3,x1,y1);
getch();
closegraph();
}
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 18
ISI-Prvasrednjainformatičkaškolasp.j.
Biblioteka rutina za programiranje miša.
Tri su rutine glavne za programiranje miša:
 int mousex( )
int mousey( )
vraćaju trenutne x i y koordinate miša u grafičkom prozoru. Ako miš još nije bio u grafičkom prozoru
tada su obje koordinate jednake nuli. U situaciji kad je miš već bio u grafičkom prozoru ali je izašao van
na bilo kojoj strani prozora tada su vrijednosti koordinata jednake zadnjoj poznatoj poziciji miša
neposredno pred izlazak iz prozora.
 bool ismouseclick(kind) Ova funkcija vraća vrijednost true ako je NEizvršen specificirani
događaj. Argumenti funkcije ismouseclick su konstante sadržane u winbgim.h datoteci:
WM_MOUSEMOVE ....... detekcija pomaka miša
WM_LBUTTONDBLCLK ... detekcija lijevog dvo-klika
WM_LBUTTONDOWN ..... detekcija pritska lijeve tipke miša
WM_LBUTTONUP ....... detekcija otpuštanja lijeve tipke miša
WM_MBUTTONDBLCLK ... detekcija dvo-klika srednje tipke (ili kotačića)
WM_MBUTTONDOWN ..... detekcija pritiska srednje tipke (kotačića) miša
WM_MBUTTONUP ....... detekcija otpuštanja srednje tipke (kotačića) miša
WM_RBUTTONDBLCLK ... detekcija desnog dv-klika
WM_RBUTTONDOWN ..... detekcija pritiska desne tipke miša
WM_RBUTTONUP ....... detekcija otpuštanja desne tipke miša
[Opaska autora rutina za miša: Rukovatelji srednje tipke miša nisu radili na mom računalu. Nažalost,
još nisam stigao otkriti razlog – moguće i neispravan miš ili pak bug u mom programu...]
E, sad, malo "filozofije"... Programiranje miša, tipkovnice i ostalih uređaja "prikopčanih" na računalo spada
pojmovno u tzv. "event-driven programming" – dakle, programiranje događaja (eventa). Radnje koje radimo s
mišem su za računalo nekakvi "događaji" pa stoga događaje koje proizvodimo mišem (eng. mouse event)
možemo obrađivati (ili slobodno rečeno hvatati) pozivanjem funkcije getmouseclick (koja nam daje,
očitava koordinate događaja – poziciju miša u pixelima), ili pozivanjem funkcije clearmouseclick (koja
obrađuje određeni događaj (ili radnju) s mišem bez dostavljanja koordinata). Pogledajmo detaljniji opis tih
funkcija u nastavku priče.
void getmouseclick(kind, int& xint& y) This function sets x and y to the pixel coordinates of an
unprocessed event of the specified kind. If there is no such event, then the function sets both x and y to -1.
The value of the argument kind may be any of the constants listed above. After callinggetmouseclick,
for a particular kind of event, the ismouseclick will return false for that kind of event until another such
event occurs.
void clearmouseclick(kind) This is just like getmouseclick, except it does not provide the x and
y coordinates of the event. The value of the argument kind may be any of the constants listed above.
After calling clearmouseclick, for a particular kind of event, the ismouseclick will return false
for that kind of event until another such event occurs.
void registermousehandler(kind, h) Most mouse processing can be carried out with
the ismouseclick and getmouseclick. But sometimes you need more control. In general, you can
obtain more control by writing a different "handler function" to handle each different kind of mouse event,
and you "register" each of your handlers by calling registermousehandler. The first argument
to registermousehandler is one of the constants listed above. The second argument
to registermousehandler must be the name of the handler function that you wrote. This function
must be a void function with two int parameters. Whenever the specified mouse event occurs, your handler
will be called and the two int parameters will be the x and y positions where the event happened.
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 19
ISI-Prvasrednjainformatičkaškolasp.j.
Funkcije za programiranje miša
Sljedeći niz naredaba služi za precizno "hvatanje" radnji s mišem odnosno njihovo "čišćenj" iz
priručne memorije (buffera).
Funkcije ZA PROGRAMIRANJE MIŠA
Pozicija miša
mousex()
x-koordinata miša (u pixelima,
naravno)
mousey() y-koordinata miša
Pomak
ismouseclick(WM_MOUSEMOVE) "hvatanje" pomicanja miša
clearmousclick(WM_MOUSEMOVE) Brisanje iz pomaka iz buffera
Pritisnuta
LIJEVA tipka
ismouseclick(WM_LBUTTONDOWN) Lijeva tipka miša pritisnuta (i držimo ju)
clearmousclick(WM_LBUTTONDOWN)
ismouseclick(WM_LBUTTONDOWN)
LIJEVI DVOklik
clearmousclick(WM_LBUTTONDBCLICK)
ismouseclick(WM_LBUTTONDBCLICK) Dvoklik LIJEVOM tipkom miša
Pritisnuta
DESNA tipka
clearmousclick (WM_RBUTTONDOWN)
ismouseclick (WM_RBUTTONDOWN) Desna tipka pritisnuta (i držimo ju)
DESNI DVOklik
ismouseclick(WM_RBUTTONDBCLICK) Dvoklik DESNOM tipkom miša
clearmousclick (WM_RBUTTONDBCLICK)
Pritisnuta
SREDNJA t.
clearmousclick (WM_MBUTTONDOWN)
ismouseclick (WM_MBUTTONDOWN) SREDNJA tipka pritisnuta i zadržana
SREDNJI
DVOklik
ismouseclick(WM_ MBUTTONDBCLICK) Dvoklik SREDNJOM tipkom miša
clearmousclick (WM_MBUTTONDBCLICK)
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 20
ISI-Prvasrednjainformatičkaškolasp.j.
Primjer programiranja miša s ismouseclick i getmouseclick funkcijama
Pretpostavimo da želite programirati zaustavljanje izvođenja programa koje biva prekinuto klikom na lijevu
tipku miša (eng. "wait for a left mouse click"). Nakon toga program će ispisati zadnje x,y koordinate na kojima je
miš bio u grafičkom prozoru. Pogledajmo funkciju koja obavlja takav zadatak:
void cekaj_lijevi_klik( )
{
const int DELAY = 50; // milisekunde zadrške prije provjere
int x, y;
while (!ismouseclick(WM_LBUTTONDOWN))
delay(DELAY);
getmouseclick(WM_LBUTTONDOWN, x, y);
cout << "Najzadnji lijevi klik na: " << x << " " << y << endl;
}
Primjer rutine za miša s rukovateljem (eng. mouse handler)
Pretpostavimo da želite ispisati poruku s x i y koordinatama pozicije miša kad god je kliknuta desna tipka miša.
Tada ćete početi s pisanjem handler funkcije poput ove:
void moj_desnokliki_handler(int x, int y)
{
cout << "Desni klik miša na: "
<< x << " and " << y << endl;
}
E, sada negdje u svom programu (nakon što ste inicijalizirali grafički prozor), morate registrirati ovaj fini handler
naredbom:
registermousehandler(WM_RBUTTONDOWN, my_right_click_handler);
U pravilu posao koji obavlja handler mora biti što kraći. Ako trebate izvršiti puno posla, mijenjajte handlerom
neku globalnu varijablu koja će kasnije biti okidač tog većeg posla (u pravilu nekog duljeg programskog koda)!
Na taj način će handler promptno odgovarati (vraćati će se brzo).
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 21
ISI-Prvasrednjainformatičkaškolasp.j.
PRIMJER: Unos koordinata poligona mišem
...uz istovremeno crtanje tog poligona. Svaki vrh poligona ujedno je iscrtan malom kružnicom uz koju
se ispisuje i redni broj točke poligona:
#include <stdio.h>
#include <winbgim.h>
#define CRVENA 4
#define BIJELA 15
#define ZELENA 2
int main()
{
int cnt=0;
int x, y
int X[50], Y[50];
char brt[2];
initwindow(400,300); //otvori graficki prozor velicine 400x300 pixela
setbkcolor(BIJELA); //boja podloge neka bude BIJELA
cleardevice(); //obriši prozor
while (!kbhit()) //vrti petlju sve dok korisnik ne pritisne neku tipku tipkovnice
{
if (ismouseclick(WM_LBUTTONDOWN)) //...ako je LIJEVI klik napravljen tada
{
cnt++; //povećaj varijablu cnt za 1
X[cnt]=mousex(); //spremi x-koord. miša u polje X[cnt]
Y[cnt]=mousey(); //spremi y-koord. miša u polje Y[cnt]
setcolor(CRVENA); //postavi crvenu boju pera
circle(X[cnt],Y[cnt],3); //nacrtaj malu crvenu kružnicu na koord. točke
sprintf(brt,"%d",cnt); //zapiši brojač cnt kao tekst u varijablu brt
outtextxy(X[cnt],Y[cnt],brt); //ispiši u graf. prozor broj točke -> brt
setcolor(ZELENA); //promjena boje pera u ZELENU
if (cnt>1) line(X[cnt-1],Y[cnt-1],X[cnt],Y[cnt]); //crtaj spojnice tek kad je 2. točka klknuta...
clearmouseclick(WM_LBUTTONDOWN); //OBAVEZNO!!! poništi događaj LBUTTON...
}
if (ismouseclick(WM_RBUTTONDOWN)) //ako je DESNI klik napravljen
{
line(X[cnt],Y[cnt],X[1],Y[1]); //zatvori poligon!
outtext("KRAJ"); //ispiši KRAJ u grafičkom prozoru
}
}
//...program se i dalje "vrti" u petlji i prekida se tek pritiskom na neku tipku tipkovnice
closegraph(); //zatvori graficki prozor
return 0;
}
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 22
ISI-Prvasrednjainformatičkaškolasp.j.
Grafičke rutine u BGI biblioteci
Inicijalizacija grafike:
Standardna inicijalizacija BGI grafike kreće pozivom funkcije detectgraph i pozivom funkcije initgraph.
Dakle, možete i dalje koristiti taj, standardan način (uobičajen u vrijeme DOS-a) ili ćete koristiti novu
jedinstvenu funkciju initwindow. Funkcija ima dva argumenta koji definiraju dimenzije grafičkog prozora u
pikselima (širinu i visinu). Na primjer, možete kreirati prozor koji je 450 piksela širok i 350 piksela visok
sljedećom naredbom:
initwindow(450, 350);
BOJE u Winbgim
Winbgim paket podržava dva sustava boja koji se mogu koristiti s bilo kojom funkcijom koja očekuje boje kao
argumente: šesnaest uobičajenih BGI boja označenih cjelobrojnim vrijednostima (integer) od 0 do 15, kojima
možemo dati simbolička imena:
num.
oznaka
boja engleski naziv hrvatski naziv
0 BLACK CRNA
1 BLUE PLAVA
2 GREEN ZELENA
3 CYAN CIJAN
4 RED CRVENA
5 MAGENTA MAGENTA
6 BROWN SMEĐA
7 LIGHTGRAY SVIJETLOSIVA
8 DARKGRAY TAMNOSIVA
9 LIGHTBLUE SVIJETLOPLAVA
10 LIGHTGREEN SVIJETLOZELENA
11 LIGHTCYAN SVIETLOCIJAN
12 LIGHTRED SVIJETLOCRVENA
13 LIGHTMAGENTA SVIJETLOMAGENTA
14 YELOW ŽUTA
15 WHITE BIJELA
RGB boje
Boja može biti zadana pomoću tri komponente: crvene, zelene i plave uporabom makro naredbe COLOR(r,g,b).
Svaki od r,g,b argumenata mora biti broj u rasponu od 0 do 255. Npr. COLOR(255,100,0) je pretežno crvena
boja s dodatkom zelene i bez plave komponente. Ili npr. COLOR(128,128,128) reprezentira svijetlo sivu boju,
dok je COLOR (255,255,255) čista bijela boja. Ove boje također mogu biti očitane s ekrana pomoću BGI funkcije
getbkcolor.
Sljedeće makro naredbe (RED_VALUE, GREEN_VALUE, BLUE_VALUE, IS_BGI_COLOR and IS_RGB_COLOR)
objašnjene su u sljedećem primjeru:
setcolor(BLUE); // Change drawing color to BLUE.
setcolor(COLOR(255,100,0); // Change drawing color to reddish-green.
setpalette(4, BLUE); // Change palette entry 4 to BLUE.
setpalette(4, COLOR(9,9,9));// Change palette entry 4 to nearly black.
int current = getcolor( ); // Set current to current drawing color.
if (IS_BGI_COLOR(current)) // Check whether it is a BGI color.
cout << "Current BGI drawing color is: " << current << end;
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 23
ISI-Prvasrednjainformatičkaškolasp.j.
if (IS_RGB_COLOR(current)) // Check whether it is an RGB color.
cout << "Current RGB drawing color has these components:n"
<< "Red: " << RED_VALUE(current) << 'n'
<< "Green: " << GREEN_VALUE(current) << 'n'
<< "Blue: " << BLUE_VALUE(current) << 'n'
int getdisplaycolor(int color)
Aktualna boja postavljena na zaslon naredbom putpixel možda neće odgovarati egzaktnoj RGB boji koju
smo željeli postići zbog ograničenja grafičkog moda koji je trenutno aktivan. Povratna vrijednost ove funkcije
daje vrijednost koja aktualna boja bi bila vidljiva na ekranu za zadane parametre boje.
Upravljanje ulaza preko TIPKOVNICE
Imamo na raspolaganju tri funkcije koje su originalni dio Borlandovog conio.h. Ove su funkcije sadržane u
winbgim.h i nema potrebe za uključivanjem conio.h:
void delay(int milisec) – zaustavlja računanje za specificirani broj milisekundi
int getch( ) – "hvata" tipku koju smo odtipkali i ne zaustavlja program onom dosadnom frazom ...press
any key to continue. Očitana tipka je u obliku ASCII vrijednosti. Ako ju želite pohraniti kao odgovarajući
znak na tipkovnici tada trebate napraviti pretvorbu: c = (char) getch( );
Ako pritisnete neku tipku s numeričke tipkovnice (strelice, Home, itd.) tada funkcija getch prvo vraća
vrijednost nula (0) a tek u sljedećem pozivu vraća nešto od sljedećeg:
KEY_HOME
KEY_UP
KEY_PGUP
KEY_LEFT
KEY_CENTER
KEY_RIGHT
KEY_END
KEY_DOWN
KEY_PGDN
KEY_INSERT
KEY_DELETE
int kbhit( ) - vraća 0 (nulu) ako niti jedna tipka nije pritisnuta (preciznije: The kbhit function returns 0 if
there are no characters now waiting to be read (with getch). It returns a non-zero if there are some
characters waiting to be read.)
Napredne grafičke naredbe u BGI biblioteci
Podrška za dvostruko baferiranje (Double-Buffering)
U postojeći BGI milje Adrian Sandor dodao je svije funkcije, getactivepage() and getvisualpage()za
podršku dvostrukog baferiranja koje omogućuje animiranu grafiku. One vraćaju broj stranice aktivne stranice
(gdje se crtež trenutno nalazi) i vidljive stranice (one koju trenutno gledamo). Originalna winbgi biblioteka
dizajnirana je za podršku do 16 stranica, ali winbgim koristi stranicu 1 i 2.
Podrška za ispis na grafički prozor
Dodan je izlazni kanal, bgiout. Njegova uporaba opisana je u bgiout.html.
Podrška za štampanje, učitavanje i zapisivanje grafike
Grafički prozor sada ima print opciju u windows meniju tako da korisnik može štampati grafički ekran u bilo
kom trenutku. To su sljedeće funkcije:
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 24
ISI-Prvasrednjainformatičkaškolasp.j.
 getimage
 imagesize
 printimage
 putimage
 readimagefile
 writeimagefile
Podrška za višestruke prozore
Initwindow funkcija može biti pozvana višestruko kako bi se moglo kreirati više od jednog grafičkog prozora.
The initwindow documentation describes how these multiple windows are used.
Ostala dokumentacija za proučavanje BGI grafike
 Winbgim functions documentation.
 Konstantin Knizhnik's original documentation.
 graphics.h header fajl.
 source code.
 Sample programs: bgidemo0.cpp (extensive program), bgidemo1.cpp (shows
registermousehandler), bgidemo2.cpp (shows COLOR macro), bgidemo3.cpp(shows COLOR
again), bgidemo4.cpp (shows getmouseclick) that use the winbgim library.
 A sample program testget.cpp that uses getch and also shows how to print numbers in graphics mode.
 Double-buffering Example dblbuff.cpp.
Kako ukloniti konzolni (tzv. DOS) prozor?
Primjetili ste da svaki program koji kompilirate s g++ ili bgi++ uvijek otvara DOS prozor. Ako želite spriječiti
otvaranje ovog prozora tada dodajte opciju:
-mwindows u kompajlersku liniju (odmah iza g++ ili bgi++).
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 25
ISI-Prvasrednjainformatičkaškolasp.j.
Borland Graphics Interface (BGI) for Windows
Version 6.0, August 9, 2004
Sljedeći popis funkcija pretežno je sastavljen od izvornih funkcija iz Borland Graphics Interface-a za
DOS programe (razvijenih u tvrtki Borland prije kojih 25 godina...). BGI grafičke funkcije mogu također
biti uptrebljene u Windows programima kreiranim s Borland 5.0 prevoditeljem kao i GNU C++
compiler prevoditeljem i vjerojatno još nekim drugim prevoditeljima. Dodatne Windows funkcije su
razvijene i opisane na linku: www.cs.colorado.edu/~main/cs1300/doc/bgi/bgi.html. ove funkcije
obilježene su oznakom . Također, sve funkcije koje koriste boju mogu se koristiti u RGB sustavu
boja (RGB colors).
U nastavku je abecedni popis BGI funkcija s linkovima na stranicu s uputama i primjerom uporabe
svake od funkcija. Može se dogoditi da s vremenom linkovi budu ugašeni! (Još uvijek rade!)
FUNKCIJE:
void arc (int x, int y, int stangle, int endangle, int radius);
void bar (int left, int top, int right, int bottom);
void bar3d (int left, int top, int right, int bottom, int depth, int topflag);
ostringstream bgiout;
void circle (int x, int y, int radius);
void cleardevice (void);
void clearmouseclick(int kind);
void clearviewport (void);
void closegraph (int window=ALL_WINDOWS);
int converttorgb (int color);
void delay (int millisec);
void detectgraph (int *graphdriver, int *graphmode);
void drawpoly (int numpoints, int *polypoints);
void ellipse (int x, int y, int stangle, int endangle, int xradius, int yradius);
void fillellipse (int x, int y, int xradius, int yradius);
void fillpoly (int numpoints, int *polypoints);
void floodfill (int x, int y, int border);
int getactivepage (void);
void getarccoords (struct arccoordstype *arccoords);
void getaspectratio (int *xasp, int *yasp);
int getbkcolor (void);
int getch (void);
int getcolor (void);
int getcurrentwindow (void);
struct palettetype* getdefaultpalette (void);
int getdisplaycolor (int color);
char* getdrivername (void);
void getfillpattern (char *pattern);
void getfillsettings (struct fillsettingstype *fillinfo);
int getgraphmode (void);
void getimage (int left, int top, int right, int bottom, void *bitmap);
void getlinesettings (struct linesettingstype *lineinfo);
int getmaxcolor (void);
int getmaxmode (void);
int getmaxheight (void);
int getmaxwidth (void);
int getmaxx (void);
int getmaxy (void);
char* getmodename (int mode_number);
void getmoderange (int graphdriver, int *lomode, int *himode);
void getmouseclick(int kind, int& x, int& y);
void getpalette (struct palettetype *palette);
int getpalettesize (void);
int getpixel (int x, int y);
void gettextsettings (struct textsettingstype *texttypeinfo);
void getviewsettings (struct viewporttype *viewport);
int getvisualpage (void);
int getwindowheight (void);
int getwindowwidth (void);
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 26
ISI-Prvasrednjainformatičkaškolasp.j.
int getx (void);
int gety (void);
void graphdefaults (void);
char* grapherrormsg (int errorcode);
int graphresult(void);
unsigned imagesize (int left, int top, int right, int bottom);
void initgraph (int *graphdriver, int *graphmode, char *pathtodriver);
int initwindow (int width, int height, const char* title="Windows BGI", int left=0, int top=0,
bool dbflag=false, bool closeflag=true);
int installuserdriver (char *name, int huge (*detect)(void));
int installuserfont (char *name);
bool ismouseclick(int kind);
int kbhit (void);
void line (int x1, int y1, int x2, int y2);
void linerel (int dx, int dy);
void lineto (int x, int y);
int mousex (void);
int mousey (void);
void moverel (int dx, int dy);
void moveto (int x, int y);
void outtext (char *textstring);
void outtextxy (int x, int y, char *textstring);
void pieslice (int x, int y, int stangle, int endangle, int radius);
void printimage (const char* title=NULL, double width_inches=7,
double border_left_inches=0.75, double border_top_inches=0.75,
int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX);
void putimage (int left, int top, void *bitmap, int op);
void putpixel (int x, int y, int color);
void readimagefile (const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX);
void rectangle (int left, int top, int right, int bottom);
int registerbgidriver (void (*driver)(void));
int registerbgifont (void (*font)(void));
void registermousehandler (int kind, void h(int, int));
void restorecrtmode (void);
RGB functions:
COLOR(r,g,b),
RED_VALUE(v), GREEN_VALUE(v), BLUE_VALUE(v),
IS_BGI_COLOR(v), IS_RGB_COLOR(v)
void sector (int x, int y, int stangle, int endangle, int xradius, int yradius);
void setactivepage (int page);
void setallpalette (struct palettetype *palette);
void setaspectratio (int xasp, int yasp);
void setbkcolor (int color);
void setcolor (int color);
void setcurrentwindow (int window);
void setmousequeuestatus(int kind, bool status=true);
void setfillpattern (char *upattern, int color);
void setfillstyle (int pattern, int color);
unsigned setgraphbufsize (unsigned bufsize);
void setgraphmode (int mode);
void setlinestyle (int linestyle, unsigned upattern, int thickness);
void setpalette (int colornum, int color);
void setrgbpalette (int colornum, int red, int green, int blue);
void settextjustify (int horiz, int vert);
void settextstyle (int font, int direction, int charsize);
void setusercharsize (int multx, int divx, int multy, int divy);
void setviewport (int left, int top, int right, int bottom, int clip);
void setvisualpage (int page);
void setwritemode (int mode);
int showerrorbox (const char *message);
int swapbuffers (void);
int textheight (char *textstring);
int textwidth (char *textstring);
void writeimagefile (const char* filename=NULL,double width_inches=7, double
border_left_inches=0.75, double border_top_inches=0.75, int left=0, int top=0, int
right=INT_MAX, int bottom=INT_MAX);
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 27
ISI-Prvasrednjainformatičkaškolasp.j.
Koje su to naredbe u winbgim.h?
WinBGIm donosi preko devedeset novih funkcija koje možemo koristiti u našim programima.
Međutim još moramo naučiti i KAKO – treba se još sprijateljiti sa sintaksom i logikom korištenja gore
navedenih mogućnosti.
Novu paletu funkcija možemo grupirati po sljedećim područjima:
CRTAJUĆE funkcije (eng. Drawing Functions)
void arc (int x, int y, int stangle, int endangle, int radius );
void bar (int left, int top, int right, int bottom );
void bar3d (int left, int top, int right, int bottom, int depth, int topflag );
void circle (int x, int y, int radius );
void drawpoly (int n_points, int* points);
void ellipse (int x, int y, int stangle, int endangle, int xradius, int yradius );
void fillellipse (int x, int y, int xradius, int yradius );
void fillpoly (int n_points, int* points);
void floodfill (int x, int y, int border );
void line (int x1, int y1, int x2, int y2 );
void linerel (int dx, int dy );
void lineto( int x, int y );
void pieslice( int x, int y, int stangle, int endangle, int radius );
void putpixel( int x, int y, int color );
void rectangle( int left, int top, int right, int bottom );
void sector( int x, int y, int stangle, int endangle, int xradius, int yradius );
RAZNE funkcije (eng. Miscellaneous Functions)
int getdisplaycolor( int color );
int converttorgb( int color );
void delay( int msec );
void getarccoords( arccoordstype *arccoords );
int getbkcolor( );
int getcolor( );
void getfillpattern( char *pattern );
void getfillsettings( fillsettingstype *fillinfo );
void getlinesettings( linesettingstype *lineinfo );
int getmaxcolor( );
int getmaxheight( );
int getmaxwidth( );
int getmaxx( );
int getmaxy( );
bool getrefreshingbgi( );
int getwindowheight( );
int getwindowwidth( );
int getpixel( int x, int y );
void getviewsettings( viewporttype *viewport );
int getx( );
int gety( );
void moverel( int dx, int dy );
void moveto( int x, int y );
void refreshbgi(int left, int top, int right, int bottom);
void refreshallbgi( );
void setbkcolor( int color );
void setcolor( int color );
void setfillpattern( char *upattern, int color );
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 28
ISI-Prvasrednjainformatičkaškolasp.j.
void setfillstyle( int pattern, int color );
void setlinestyle( int linestyle, unsigned upattern, int thickness );
void setrefreshingbgi(bool value);
void setviewport( int left, int top, int right, int bottom, int clip );
void setwritemode( int mode );
"PROZORSKE" funkcije (eng. Window Creation / Graphics Manipulation)
void initgraph (int *graphdriver, int *graphmode, char *pathtodriver );
int initwindow (int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false,
bool closeflag=true );
void cleardevice();
void clearviewport();
void closegraph (int wid=ALL_WINDOWS );
void detectgraph (int *graphdriver, int *graphmode);
void getaspectratio (int *xasp, int *yasp);
char *getdrivername ();
int getgraphmode();
int getmaxmode();
char *getmodename (int mode_number);
void getmoderange (int graphdriver, int *lomode, int *himode );
void graphdefaults( );
char *grapherrormsg( int errorcode );
int graphresult( );
int installuserdriver( char *name, int *fp ); // Not available in WinBGI
int installuserfont( char *name ); // Not available in WinBGI
int registerbgidriver( void *driver ); // Not available in WinBGI
int registerbgifont( void *font ); // Not available in WinBGI
void restorecrtmode( );
void setaspectratio( int xasp, int yasp );
unsigned setgraphbufsize( unsigned bufsize ); // Not available in WinBGI
void setgraphmode( int mode );
void showerrorbox( const char *msg = NULL );
Interakcija s korisnikom (eng. User Interaction)
int getch( );
int kbhit( );
User-Controlled Window Functions (winbgi.cpp)
int getcurrentwindow( );
void setcurrentwindow( int window );
Double buffering support (winbgi.cpp)
int getactivepage( );
int getvisualpage( );
void setactivepage( int page );
void setvisualpage( int page );
void swapbuffers( );
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 29
ISI-Prvasrednjainformatičkaškolasp.j.
"SLIKOVNE" funkcije (rasterska grafika) (eng. Image Functions (drawing.cpp))
unsigned imagesize( int left, int top, int right, int bottom );
void getimage( int left, int top, int right, int bottom, void *bitmap );
void putimage( int left, int top, void *bitmap, int op );
void printimage(
const char* title=NULL,
double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75,
int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
void readimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX
);
void writeimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
TEKSTNE iliti "PISAJUĆE" funkcije (eng. Text Functions (text.cpp))
void gettextsettings(struct textsettingstype *texttypeinfo);
void outtext(char *textstring);
void outtextxy(int x, int y, char *textstring);
void settextjustify(int horiz, int vert);
void settextstyle(int font, int direction, int charsize);
void setusercharsize(int multx, int divx, int multy, int divy);
int textheight(char *textstring);
int textwidth(char *textstring);
extern std::ostringstream bgiout;
void outstream(std::ostringstream& out=bgiout);
void outstreamxy(int x, int y, std::ostringstream& out=bgiout);
"MIŠJE" funkcije (eng. Mouse Functions (mouse.cpp))
void clearmouseclick( int kind );
void clearresizeevent( );
void getmouseclick( int kind, int& x, int& y );
bool ismouseclick( int kind );
bool isresizeevent( );
int mousex( );
int mousey( );
void registermousehandler( int kind, void h( int, int ) );
void setmousequeuestatus( int kind, bool status=true );
Upravljanje paletama boja (eng. Palette Functions)
palettetype *getdefaultpalette( );
void getpalette( palettetype *palette );
int getpalettesize( );
void setallpalette( palettetype *palette );
void setpalette( int colornum, int color );
void setrgbpalette( int colornum, int red, int green, int blue );
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 30
ISI-Prvasrednjainformatičkaškolasp.j.
FUNKCIJE, još jednom...
...još jednom, ali direktno iz WinBGIm-a. Uočite crvene markacije, mjesta s greškama koje su
ispravljene u priloženim datotekama (JT):
// Drawing Functions
void arc( int x, int y, int stangle, int endangle, int radius );
void bar( int left, int top, int right, int bottom );
void bar3d( int left, int top, int right, int bottom, int depth, int topflag );
void circle( int x, int y, int radius );
void cleardevice( );
void clearviewport( );
void drawpoly(int n_points, int* points);
void ellipse( int x, int y, int stangle, int endangle, int xradius, int yradius );
void fillellipse( int x, int y, int xradius, int yradius );
void fillpoly(int n_points, int* points);
void floodfill( int x, int y, int border );
void line( int x1, int y1, int x2, int y2 );
void linerel( int dx, int dy );
void lineto( int x, int y );
void pieslice( int x, int y, int stangle, int endangle, int radius );
void putpixel( int x, int y, int color );
void rectangle( int left, int top, int right, int bottom );
void sector( int x, int y, int stangle, int endangle, int xradius, int yradius );
// Miscellaneous Functions
int getdisplaycolor( int color );
int converttorgb( int color );
void delay( int msec );
void getarccoords( arccoordstype *arccoords );
int getbkcolor( );
int getcolor( );
void getfillpattern( char *pattern );
void getfillsettings( fillsettingstype *fillinfo );
void getlinesettings( linesettingstype *lineinfo );
int getmaxcolor( );
int getmaxheight( );
int getmaxwidth( );
int getmaxx( );
int getmaxy( );
bool getrefreshingbgi( );
int getwindowheight( );
int getwindowwidth( );
int getpixel( int x, int y );
void getviewsettings( viewporttype *viewport );
int getx( );
int gety( );
void moverel( int dx, int dy );
void moveto( int x, int y );
void refreshbgi(int left, int top, int right, int bottom);
void refreshallbgi( );
void setbkcolor( int color );
void setcolor( int color );
void setfillpattern( char *upattern, int color );
void setfillstyle( int pattern, int color );
void setlinestyle( int linestyle, unsigned upattern, int thickness );
void setrefreshingbgi(bool value);
void setviewport( int left, int top, int right, int bottom, int clip );
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 31
ISI-Prvasrednjainformatičkaškolasp.j.
void setwritemode( int mode );
// Window Creation / Graphics Manipulation
void closegraph( int wid=ALL_WINDOWS );
void detectgraph( int *graphdriver, int *graphmode );
void getaspectratio( int *xasp, int *yasp );
char *getdrivername( );
int getgraphmode( );
int getmaxmode( );
char *getmodename( int mode_number );
void getmoderange( int graphdriver, int *lomode, int *himode );
void graphdefaults( );
char *grapherrormsg( int errorcode );
int graphresult( );
void initgraph( int *graphdriver, int *graphmode, char *pathtodriver );
int initwindow
( int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool
closeflag=true );
int installuserdriver( char *name, int *fp ); // Not available in WinBGI
int installuserfont( char *name ); // Not available in WinBGI
int registerbgidriver( void *driver ); // Not available in WinBGI
int registerbgifont( void *font ); // Not available in WinBGI
void restorecrtmode( );
void setaspectratio( int xasp, int yasp );
unsigned setgraphbufsize( unsigned bufsize ); // Not available in WinBGI
void setgraphmode( int mode );
void showerrorbox( const char *msg = NULL );
// User Interaction
int getch( );
int kbhit( );
// User-Controlled Window Functions (winbgi.cpp)
int getcurrentwindow( );
void setcurrentwindow( int window );
// Double buffering support (winbgi.cpp)
int getactivepage( );
int getvisualpage( );
void setactivepage( int page );
void setvisualpage( int page );
void swapbuffers( );
// Image Functions (drawing.cpp)
unsigned imagesize( int left, int top, int right, int bottom );
void getimage( int left, int top, int right, int bottom, void *bitmap );
void putimage( int left, int top, void *bitmap, int op );
void printimage(
const char* title=NULL,
double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75,
int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 32
ISI-Prvasrednjainformatičkaškolasp.j.
void readimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX
);
void writeimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
// Text Functions (text.cpp)
void gettextsettings(struct textsettingstype *texttypeinfo);
void outtext(char *textstring);
void outtextxy(int x, int y, char *textstring);
void settextjustify(int horiz, int vert);
void settextstyle(int font, int direction, int charsize);
void setusercharsize(int multx, int divx, int multy, int divy);
int textheight(char *textstring);
int textwidth(char *textstring);
extern std::ostringstream bgiout;
void outstream(std::ostringstream& out=bgiout);
void outstreamxy(int x, int y, std::ostringstream& out=bgiout);
// Mouse Functions (mouse.cpp)
void clearmouseclick( int kind );
void clearresizeevent( );
void getmouseclick( int kind, int& x, int& y );
bool ismouseclick( int kind );
bool isresizeevent( );
int mousex( );
int mousey( );
void registermousehandler( int kind, void h( int, int ) );
void setmousequeuestatus( int kind, bool status=true );
// Palette Functions
palettetype *getdefaultpalette( );
void getpalette( palettetype *palette );
int getpalettesize( );
void setallpalette( palettetype *palette );
void setpalette( int colornum, int color );
void setrgbpalette( int colornum, int red, int green, int blue );
// Color Macros
#define IS_BGI_COLOR(v) ( ((v) >= 0) && ((v) < 16) )
#define IS_RGB_COLOR(v) ( (v) & 0x03000000 )
#define RED_VALUE(v) int(GetRValue( converttorgb(v) ))
#define GREEN_VALUE(v) int(GetGValue( converttorgb(v) ))
#define BLUE_VALUE(v) int(GetBValue( converttorgb(v) ))
#undef COLOR
int COLOR(int r, int g, int b); // No longer a macro
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 33
ISI-Prvasrednjainformatičkaškolasp.j.
Napredno korištenje BGI grafike
initwindow
Syntax
#include "graphics.h"
int initwindow(int width, int height, const char* title="Windows
BGI", int left=0, int top=0, bool dbflag=false, closeflag=true);
Description
The initwindow function is available in the winbgim implementation of BGI graphics. You do not need
to include conio.h; just include graphics.h. The function initializes the graphics system by opening a
graphics window of the specified size. The first two parameters (width and height) are required, but all
other parameters have default values.
The title parameter is the title that will be printed at the top of the window (with a default of
"Windows BGI".)
The left and top parameters determine the screen coordinates of the left and top sides of the window.
The dbflag parameter determines whether double-buffering for the window is automatically turned on
as described in the swapbuffers function (true means that double-buffering will be turned on).
If the closeflag parameter is true, then the user can click on the window's close button to shut down
the entire program.
Return Value
The original version of initgraph was a void function (with no flag argument), and only one graphics
window could be created in any program. The new version allows multiple graphics windows to be
created. The return value from the new initwindow function is a unique int identifier that can be used
as an argument to setcurrentwindow in order to set which of several windows is currently being used.
Immediately after calling initwindow, the current window is always the window that was just created.
See also
closegraph; getcurrentwindow; getmaxheight; getmaxwidth; initgraph; setcurrentwindow;
swapbuffers
Example
/* initwindow example */
#include "graphics.h"
int main(void)
{
/* initialize graphics window at 400 x 300 */
initwindow(400, 300);
/* draw a line */
line(0, 0, getmaxx(), getmaxy());
/* clean up */
getch();
closegraph();
return 0;
}
/* initwindow example with two windows */
#include "graphics.h"
int main(void)
{
int wid1, wid2;
/* initialize graphics windows */
wid1 = initwindow(400, 300);
wid2 = initwindow(300, 400, 200, 100);
/* draw lines */
setcurrentwindow(wid1);
line(0, 0, getmaxx(), getmaxy());
setcurrentwindow(wid2);
line(0, 0, getmaxx(), getmaxy());
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 34
ISI-Prvasrednjainformatičkaškolasp.j.
/* clean up */
getch();
closegraph();
return 0;
}
setcurrentwindow
Syntax
#include "graphics.h"
void setcurrentwindow(int window);
Description
The setcurrentwindow function is available in the winbgim implementation of BGI graphics. You do
not need to include conio.h; just include graphics.h.
The function changes the current window for all graphics operations to the specified window. This
window number must be a number returned by the initiwindow functiion. The current window is the
window where all other graphics operations will take place.
Note: Initwindow and initgraph both set the current window to the newly created window, so there is
no need to call setcurrentwindow immediately after opening a new window. parameters have default
values.
See also
getcurrentwindow; initgraph; initwindow
Example
/* setcurrentwindow example */
#include
int main(void)
{
int big;
int w, w_right, w_below ;
int width, height; // Total width and height of w_left;
big = initwindow(getmaxwidth( ), getmaxheight( ), "Big");
w = initwindow(300, 200, "Top/Left Corner");
width = getwindowwidth( );
height = getwindowheight( );
w_right = initwindow(300, 200, "Right", width, 0);
w_below = initwindow(300, 200, "Below", 0, height);
setcurrentwindow(big);
line(0, 0, getmaxwidth( )-1, getmaxheight( )-1);
/* clean up */
getch();
closegraph();
return 0;
}
getcurrentwindow
Syntax
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 35
ISI-Prvasrednjainformatičkaškolasp.j.
#include "graphics.h"
int getcurrentwindow( );
Description
The getcurrentwindow function is available in the winbgim implementation of BGI graphics. You do
not need to include conio.h; just include graphics.h.
The function gets the current window number, which is the window where all graphics operations
occur.
See also
setcurrentwindow; initgraph; initwindow
Example
/* setcurrentwindow example */
#include
void change ( int window )
{
int oldwindow = getcurrentwindow( );
setcurrentwindow(window);
// Do whatever graphics operations you like in the new current
// window...
// Restore the original window:
setcurrentwindow(oldwindow);
}
closegraph
Syntax
#include <graphics.h>
void closegraph(int wid=ALL_WINDOWS);
Description
closegraph deallocates all memory allocated by the graphics system, then restores the screen to the
mode it was in before you called initgraph. (The graphics system deallocates memory, such as the
drivers, fonts, and an internal buffer, through a call to _graphfreemem.)
Return Value
None.
Windows Notes
The windows version of closegraph has an optional parameter called wid which is the window id
(returned by initwindow) of the window that is to be closed. This parameter may also be one of two
special constant values: CURRENT_WINDOW (causing closegraph to close only the current window), or
ALL_WINDOWS (which is the default, causing closegraph to close all open graphics windows). If the
current window is closed, then there is no longer a current window and no further drawing operations
may be done until a new window is created or a current window is set by calling setcurrentwindow.
See also
initgraph; initwindow; setgraphbufsize; setcurrentwindow
Example
/* closegraph example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode, x, y;
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 36
ISI-Prvasrednjainformatičkaškolasp.j.
/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
x = getmaxx() / 2;
y = getmaxy() / 2;
/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "Press a key to close the graphics system:");
getch(); /* wait for a key */
/* closes down the graphics system */
closegraph();
printf("We're now back in text mode.n");
printf("Press any key to halt:");
getch();
return 0;
}
swapbuffers
Syntax
#include "graphics.h"
void swapbuffers( );
Description
The swapbuffers function is available in the winbgim implementation of BGI graphics. You do not need
to include conio.h; just include graphics.h. The function swaps the roles of the current active and the
current visual graphics buffers. It is equivalent to these statements:
int oldv = getvisualpage( );
int olda = getactivepage( );
setvisualpage(olda);
setactivepage(oldv);
See also
getactivepage; getvisualpage; initwindow; setactivepage; setvisualpage
getactivepage
Syntax
#include "graphics.h"
int getactivepage(void);
Description
The getactivepage function is available in the winbgim implementation of BGI graphics. getactivepage
gets the page number of the currently active page (where drawing takes place).
The active graphics page might not be the one you see onscreen, depending on how many graphics
pages are available on your system.
The original winbgi was designed to support up to 16 pages, but I have only used pages 1 and 2 myself.
NOTE: Using page number 0 might mess up the colors. I use pages 1-2 for double buffering.
Return Value
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 37
ISI-Prvasrednjainformatičkaškolasp.j.
The page number of the currently active page.
See also
getvisualpage; setactivepage; swapbuffers
getvisualpage
Syntax
#include "graphics.h"
int getvisualpage(void);
Description
The getvisualpage function is available in the winbgim implementation of BGI graphics. getvisualpage
gets the page number of the currently visable page (which is visible on the screen).
The visual graphics page might not be the one where drawing currnetly takes place.
The original winbgi was designed to support up to 16 pages, but I have only used pages 1 and 2 myself.
NOTE: Using page number 0 might mess up the colors. I use pages 1-2 for double buffering.
Return Value
The page number of the currently visible page.
See also
getactivepage; setvisualpage; swapbuffers
setactivepage
Syntax
#include <graphics.h>
void setactivepage(int page);
Description
setactivepage makes page the active graphics page. All subsequent graphics output will be directed to
that graphics page.
The active graphics page might not be the one you see onscreen, depending on how many graphics
pages are available on your system. Only the EGA, VGA, and Hercules graphics cards support multiple
pages.
Return Value
None.
See also
setvisualpage; swapbuffers
Example
/* setactivepage example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* select driver and mode that supports multiple pages */
int gdriver = EGA, gmode = EGAHI, errorcode;
int x, y, ht;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 38
ISI-Prvasrednjainformatičkaškolasp.j.
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
x = getmaxx() / 2;
y = getmaxy() / 2;
ht = textheight("W");
/* select the off screen page for drawing */
setactivepage(1);
/* draw a line on page #1 */
line(0, 0, getmaxx(), getmaxy());
/* output a message on page #1 */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "This is page #1:");
outtextxy(x, y+ht, "Press any key to halt:");
/* select drawing to page #0 */
setactivepage(0);
/* output a message on page #0 */
outtextxy(x, y, "This is page #0.");
outtextxy(x, y+ht, "Press any key to view page #1:");
getch();
/* select page #1 as the visible page */
setvisualpage(1);
/* clean up */
getch();
closegraph();
return 0;
}
setvisualpage
Syntax
#include <graphics.h>
void setvisualpage(int page);
Description
setvisualpage makes page the visual graphics page.
Return Value
None.
See also
graphresult; setactivepage; swapbuffers
Example
/* setvisualpage example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* select driver and mode that supports multiple pages */
int gdriver = EGA, gmode = EGAHI, errorcode;
int x, y, ht;
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 39
ISI-Prvasrednjainformatičkaškolasp.j.
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
x = getmaxx() / 2;
y = getmaxy() / 2;
ht = textheight("W");
/* select the off screen page for drawing */
setactivepage(1);
/* draw a line on page #1 */
line(0, 0, getmaxx(), getmaxy());
/* output a message on page #1 */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "This is page #1:");
outtextxy(x, y+ht, "Press any key to halt:");
/* select drawing to page #0 */
setactivepage(0);
/* output a message on page #0 */
outtextxy(x, y, "This is page #0.");
outtextxy(x, y+ht, "Press any key to view page #1:");
getch();
/* select page #1 as the visible page */
setvisualpage(1);
/* clean up */
getch();
closegraph();
return 0;
}
setviewport
Syntax
#include <graphics.h>
void setviewport(int left, int top, int right, int bottom, int clip);
Description
setviewport establishes a new viewport for graphics output.
The viewport corners are given in absolute screen coordinates by (left,top) and (right,bottom). The
current position (CP) is moved to (0,0) in the new window.
The parameter clip determines whether drawings are clipped (truncated) at the current viewport
boundaries. If clip is nonzero, all drawings will be clipped to the current viewport.
Return Value
If invalid input is passed to setviewport, graphresult returns -11, and the current view settings remain
unchanged.
See also
clearviewport; getviewsettings; graphresult
Example
/* setviewport example */
#include <graphics.h>
#include <stdlib.h>
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 40
ISI-Prvasrednjainformatičkaškolasp.j.
#include <stdio.h>
#include <conio.h>
#define CLIP_ON 1 /* activates clipping in viewport */
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
setcolor(getmaxcolor());
/* message in default full-screen viewport */
outtextxy(0, 0, "* <-- (0, 0) in default viewport");
/* create a smaller viewport */
setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON);
/* display some text */
outtextxy(0, 0, "* <-- (0, 0) in smaller viewport");
/* clean up */
getch();
closegraph();
return 0;
}
clearviewport
Syntax
#include <graphics.h>
void clearviewport(void);
Description
clearviewport erases the viewport and moves the CP (current position) to home (0,0), relative to the
viewport.
Return Value
None.
See also
cleardevice; getviewsettings; setviewport
Example
/* clearviewport example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#define CLIP_ON 1 /* activates clipping in viewport */
int main(void)
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 41
ISI-Prvasrednjainformatičkaškolasp.j.
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode, ht;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
setcolor(getmaxcolor());
ht = textheight("W");
/* message in default full-screen viewport */
outtextxy(0, 0, "* <-- (0, 0) in default viewport");
/* create a smaller viewport */
setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON);
/* display some messages */
outtextxy(0, 0, "* <-- (0, 0) in smaller viewport");
outtextxy(0, 2*ht, "Press any key to clear viewport:");
getch(); /* wait for a key */
clearviewport(); /* clear the viewport */
/* output another message */
outtextxy(0, 0, "Press any key to quit:");
/* clean up */
getch();
closegraph();
return 0;
}
getx
Syntax
#include <graphics.h>
int getx(void);
Description
getx finds the current graphics position's x-coordinate. The value is viewport-relative.
Return Value
getx returns the x-coordinate of the current position.
See also
getmaxx; getviewsettings; gety; moveto
Example
/* getx example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg[80];
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 42
ISI-Prvasrednjainformatičkaškolasp.j.
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
/* move to the screen center point */
moveto(getmaxx() / 2, getmaxy() / 2);
/* create a message string */
sprintf(msg, "<-(%d, %d) is the here.", getx(), gety());
/* display the message */
outtext(msg);
/* clean up */
getch();
closegraph();
return 0;
}
gety
Syntax
#include <graphics.h>
int gety(void);
Description
gety returns the current graphics position's y-coordinate. The value is viewport-relative.
Return Value
gety returns the y-coordinate of the current position.
See also
getmaxy; getviewsettings; getx; moveto
Example
/* gety example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 43
ISI-Prvasrednjainformatičkaškolasp.j.
/* move to the screen center point */
moveto(getmaxx() / 2, getmaxy() / 2);
/* create a message string */
sprintf(msg, "<-(%d, %d) is the here.", getx(), gety());
/* display the message */
outtext(msg);
/* clean up */
getch();
closegraph();
return 0;
}
moveto
Syntax
#include <graphics.h>
void moveto(int x, int y);
Description
moveto moves the current position (CP) to viewport position (x,y).
Return Value
None.
See also
moverel
Example
/* moveto example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
/* move the CP to location (20,30) */
moveto(20,30);
/* plot a pixel at the CP */
putpixel(getx(), gety(), getmaxcolor());
/* create and output a message at (20,30) */
sprintf(msg, " (%d, %d)", getx(), gety());
outtextxy(20,30, msg);
/* move to (100,100) */
moveto(100,100);
/* plot a pixel at the CP */
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 44
ISI-Prvasrednjainformatičkaškolasp.j.
putpixel(getx(), gety(), getmaxcolor());
/* create and output a message at CP */
sprintf(msg, " (%d, %d)", getx(), gety());
outtext(msg);
/* clean up */
getch();
closegraph();
return 0;
}
moverel
Syntax
#include <graphics.h>
void moverel(int dx, int dy);
Description
moverel moves the current position (CP) dx pixels in the x direction and dy pixels in the y direction.
Return Value
None.
See also
moveto
Example
/* moverel example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
/* move the CP to location (20,30) */
moveto(20,30);
/* plot a pixel at the CP */
putpixel(getx(), gety(), getmaxcolor());
/* create and output a message at (20,30) */
sprintf(msg, " (%d, %d)", getx(), gety());
outtextxy(20,30, msg);
/* move to a point a relative distance away from the current CP */
moverel(100, 100);
/* plot a pixel at the CP */
putpixel(getx(), gety(), getmaxcolor());
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 45
ISI-Prvasrednjainformatičkaškolasp.j.
/* create and output a message at CP */
sprintf(msg, " (%d, %d)", getx(), gety());
outtext(msg);
/* clean up */
getch();
closegraph();
return 0;
}
getmaxx
Syntax
#include <graphics.h>
int getmaxx(void);
Description
getmaxx returns the maximum (screen-relative) x value for the current graphics driver and mode.
For example, on a CGA in 320*200 mode, getmaxx returns 319. getmaxx is invaluable for centering,
determining the boundaries of a region onscreen, and so on.
Return Value
getmaxx returns the maximum x screen coordinate.
See also
getmaxy; getwindowwidth; getx
Example
/* getmaxx example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char xrange[80], yrange[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* convert max resolution values to strings */
sprintf(xrange, "X values range from 0..%d", getmaxx());
sprintf(yrange, "Y values range from 0..%d", getmaxy());
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, xrange);
outtextxy(midx, midy + textheight("W"), yrange);
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 46
ISI-Prvasrednjainformatičkaškolasp.j.
/* clean up */
getch();
closegraph();
return 0;
}
getwindowwidth
Syntax
#include <graphics.h>
int getwindowwidth(void);
Description
The getwindowwidth function is available in the winbgim implementation of BGI graphics. The
function returns the total width of the window including nondrawable border areas.
Return Value
getwindowwidth returns the total width of the window
See also
getmaxx; getwindowheight; getx
Example
/* getwindowwidth example */
#include <graphics.h>
int main(void)
{
int w_left, w_right;
int width; // Total width of w_left;
// Make two windows, side by side */
w_left = initwindow(300, 200);
width = getwindowwidth( );
w_right = initwindow(300, 200, width, 0);
/* clean up */
getch();
closegraph();
return 0;
}
getwindowheight
Syntax
#include <graphics.h>
int getwindowheight(void);
Description
The getwindowheight function is available in the winbgim implementation of BGI graphics. The
function returns the total height of the window including nondrawable border areas.
Return Value
getwindowheight returns the total height of the window
See also
getmaxy; getwindowwidth; gety
Example
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 47
ISI-Prvasrednjainformatičkaškolasp.j.
/* getwindowheight example */
#include <graphics.h>
int main(void)
{
int w_above, w_below;
int height; // Total height of w_above;
// Make two windows, one on top of the other */
w_above = initwindow(300, 200);
height = getwindowheight( );
w_below = initwindow(300, 200, 0, height);
/* clean up */
getch();
closegraph();
return 0;
}
setcolor
Syntax
#include <graphics.h>
void setcolor(int color);
Description
setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor. The current
drawing color is the value to which pixels are set when lines, and so on are drawn. The drawing colors
shown below are available for the CGA and EGA, respectively.
Palette Number Three Colors
0 LIGHTGREEN LIGHTRED YELLOW
1 LIGHTCYAN LIGHTMAGENTA WHITE
2 GREEN RED BROWN
3 CYAN MAGENTA LIGHTGRAY
Name Value
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
You select a drawing color by passing either the color number itself or the equivalent symbolic name
to setcolor. For example, in CGAC0 mode, the palette contains four colors: the background color, light
green, light red, and yellow. In this mode, either setcolor(3) or setcolor(CGA_YELLOW) selects a
drawing color of yellow.
Return Value
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 48
ISI-Prvasrednjainformatičkaškolasp.j.
None.
Windows Notes
The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or anRGB
color.
Example
/* setcolor example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* select driver and mode that supports multiple drawing colors */
int gdriver = EGA, gmode = EGAHI, errorcode;
int color, maxcolor, x, y;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
/* maximum color index supported */
maxcolor = getmaxcolor();
/* for centering text messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
x = getmaxx() / 2;
y = getmaxy() / 2;
/* loop through the available colors */
for (color=1; color<=maxcolor; color++) {
cleardevice(); /* clear the screen */
setcolor(color); /* select new background color */
/* output a messsage */
sprintf(msg, "Color: %d", color);
outtextxy(x, y, msg);
getch();
}
/* clean up */
closegraph();
return 0;
}
See also
getpalette ; getpalettesize ; graphresult ; setbkcolor ; setcolor
setpalette
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 49
ISI-Prvasrednjainformatičkaškolasp.j.
setbkcolor
Syntax
#include <graphics.h>
void setbkcolor(int color);
Description
setbkcolor sets the background to the color specified by color. The argument color can be a name or a
number as listed below. (These symbolic names are defined in graphics.h.)
Name Value
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
For example, if you want to set the background color to blue, you can call
setbkcolor(BLUE) /* or */ setbkcolor(1)
On CGA and EGA systems, setbkcolor changes the background color by changing the first entry in the
palette.
If you use an EGA or a VGA, and you change the palette colors with setpalette or setallpalette, the
defined symbolic constants might not give you the correct color. This is because the parameter to
setbkcolor indicates the entry number in the current palette rather than a specific color (unless the
parameter passed is 0, which always sets the background color to black).
Return Value
None.
Windows Notes
The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or anRGB
color. Also, only future drawing will use the new background color (anything currently drawn in the
old background color will stay in the old color). Calling setbkcolor(0) will change the background color
to the current color at index [0] of the palette (rather than always changing the background to black).
See also
getbkcolor; setallpalette; setcolor;setpalette
Example
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 50
ISI-Prvasrednjainformatičkaškolasp.j.
/* setbkcolor example */
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* _select driver and mode that supports multiple background colors*/
int gdriver = EGA, gmode = EGAHI, errorcode;
int bkcol, maxcolor, x, y;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %sn", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
/* maximum color index supported */
maxcolor = getmaxcolor();
/* for centering text messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
x = getmaxx() / 2;
y = getmaxy() / 2;
/* loop through the available colors */
for (bkcol=0; bkcol<=maxcolor; bkcol++) {
/* clear the screen */
cleardevice();
/* select a new background color */
setbkcolor(bkcol);
/* output a messsage */
if (bkcol == WHITE)
setcolor(EGA_BLUE);
sprintf(msg, "Background color: %d", bkcol);
outtextxy(x, y, msg);
getch();
}
/* clean up */
closegraph();
return 0;
}
getch
Syntax
#include "graphics.h"
int getch(void);
Description
The getch function is available in the winbgim implementation of BGI graphics. You do not need to
include conio.h; just include graphics.h. The function reads one character from the keyboard and
returns its ASCII value (without waiting for a return key). In order to work, the user must click in the
graphics window (i.e., the Windows focus must be in the graphics window). For special keys, the getch
function first returns ASCII 0. The next call will then return one of these special keys:
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 51
ISI-Prvasrednjainformatičkaškolasp.j.
#define KEY_HOME 71
#define KEY_UP 72
#define KEY_PGUP 73
#define KEY_LEFT 75
#define KEY_CENTER 76
#define KEY_RIGHT 77
#define KEY_END 79
#define KEY_DOWN 80
#define KEY_PGDN 81
#define KEY_INSERT 82
#define KEY_DELETE 83
#define KEY_F1 59
#define KEY_F2 60
#define KEY_F3 61
#define KEY_F4 62
#define KEY_F5 63
#define KEY_F6 64
#define KEY_F7 65
#define KEY_F8 66
#define KEY_F9 67
Return Value
The ASCII value of a key that has been pressed.
See also
kbhit
Example
#include "graphics.h"
#include <stdio.h> // Provides sprintf
#include <iostream.h> // Provides cout
void outintxy(int x, int y, int value);
int main( )
{
int i;
char c;
// Initialize the graphics window.
init_window(400, 300);
// Convert some numbers to strings and draw them in graphics window:
outtextxy(10, 10, "Here are some numbers:");
for (i = 10; i <= 100; i += 10)
outintxy(20, i+10, i);
// Get some characters from the keyboard until an X is typed:
outtextxy(20, 130, "Click in this graphics window,");
outtextxy(20, 140, "and then press arrow keys.");
outtextxy(20, 150, "Watch the console window while pressing.");
outtextxy(20, 160, "Press X to exit.");
do
{
c = (char) getch( );
if (c != 0)
cout << "That is ASCII value: " << (int) c << endl;
else
{ // Process one of the special keys:
c = (char) getch( );
switch (c)
{
case KEY_HOME: cout << "Home key." << endl; break;
case KEY_UP: cout << "Up key." << endl; break;
case KEY_PGUP: cout << "PgUp key." << endl; break;
case KEY_LEFT: cout << "Left key." << endl; break;
case KEY_CENTER: cout << "Center key." << endl; break;
case KEY_RIGHT: cout << "Right key." << endl; break;
case KEY_END: cout << "End key." << endl; break;
case KEY_DOWN: cout << "Down key." << endl; break;
case KEY_PGDN: cout << "PgDn key." << endl; break;
case KEY_INSERT: cout << "Insert key." << endl; break;
case KEY_DELETE: cout << "Delete key." << endl; break;
case KEY_F1: cout << "F1 key." << endl; break;
case KEY_F2: cout << "F2 key." << endl; break;
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 52
ISI-Prvasrednjainformatičkaškolasp.j.
case KEY_F3: cout << "F3 key." << endl; break;
case KEY_F4: cout << "F4 key." << endl; break;
case KEY_F5: cout << "F5 key." << endl; break;
case KEY_F6: cout << "F6 key." << endl; break;
case KEY_F7: cout << "F7 key." << endl; break;
case KEY_F8: cout << "F8 key." << endl; break;
case KEY_F9: cout << "F9 key." << endl; break;
default: cout << "Unknown extended key." << endl;
}
}
} while ((c != 'x') && (c != 'X'));
closegraph( );
}
void outintxy(int x, int y, int value)
{
char digit_string[20];
sprintf(digit_string, "%d", value);
outtextxy(x, y, digit_string);
}
kbhit
Syntax
#include "graphics.h"
int kbhit(void);
Description
The kbhit function is available in the winbgim implementation of BGI graphics. You do not need to
include conio.h; just include graphics.h. The function returns true (non-zero) if there is a character in
the input buffer ready to read. Otherwise it returns false. In order to work, the user must click in the
graphics window (i.e., the Windows focus must be in the graphics window).
Return Value
True (non-zero) if there is a character in the input buffer, otherwise false.
See also
getch
Example
#include "graphics.h"
#include <stdio.h> // Provides sprintf
void outintxy(int x, int y, int value);
int main( )
{
int i;
// Initialize the graphics window.
init_window(400, 300);
// Convert some numbers to strings and draw them in graphics window:
outtextxy(20, 130, "Click in this graphics window,");
outtextxy(20, 140, "and then press a key to stop.");
outtextxy(10, 10, "Here are some numbers:");
for (i = 0; !kbhit( ); i++)
{
outintxy(20 + (i/10)*40 , (i % 10)*+10, i);
delay(4000);
}
closegraph( );
}
void outintxy(int x, int y, int value)
{
char digit_string[20];
PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 53
ISI-Prvasrednjainformatičkaškolasp.j.
sprintf(digit_string, "%d", value);
outtextxy(x, y, digit_string);
}
Jt prg bg_igrafika_&_code_blocks_20121210
Jt prg bg_igrafika_&_code_blocks_20121210

More Related Content

What's hot

Uspješna prezentacija u 8 koraka
Uspješna prezentacija u 8 korakaUspješna prezentacija u 8 koraka
Uspješna prezentacija u 8 koraka
Katarina Gaži - Pavelić, mag.oec.
 
Pubertet
PubertetPubertet
Pubertet
Ajna19
 
Bezbednost na internetu
Bezbednost na internetuBezbednost na internetu
Bezbednost na internetuJelena Popara
 
Hardverske komponente PC racunara
Hardverske komponente PC racunaraHardverske komponente PC racunara
Hardverske komponente PC racunarazornik
 
Internet
InternetInternet
Internet
sejonp2708
 
Михајло Пупин 2
Михајло Пупин 2Михајло Пупин 2
Михајло Пупин 2
TimZainformisanje
 
398 dobre i loše strane interneta
398 dobre i loše strane interneta398 dobre i loše strane interneta
398 dobre i loše strane internetaPogled kroz prozor
 
Bezbednost na internetu
Bezbednost na internetuBezbednost na internetu
Bezbednost na internetu
Bezbednost Netu
 
Upotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptx
Upotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptxUpotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptx
Upotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptx
SaaBijelji1
 
Obrazac za pravdanje izostanaka roditelji
Obrazac za pravdanje izostanaka   roditeljiObrazac za pravdanje izostanaka   roditelji
Obrazac za pravdanje izostanaka roditelji
Aleksandra Gavrić Živković
 
Galileo Galilei
Galileo GalileiGalileo Galilei
Galileo Galilei
OSVB7b
 
Osnovne komponente ikt uredjaja
Osnovne komponente ikt uredjajaOsnovne komponente ikt uredjaja
Osnovne komponente ikt uredjaja
Siniša Ćulafić
 
Istorijski razvoj interneta
Istorijski razvoj internetaIstorijski razvoj interneta
Istorijski razvoj internetaDarioNaharis
 
Klima, biljni pokrov i ekološki problemi Hrvatske
Klima, biljni pokrov i ekološki problemi HrvatskeKlima, biljni pokrov i ekološki problemi Hrvatske
Klima, biljni pokrov i ekološki problemi Hrvatske
Moja Geografija
 
Zdravlje i tehnologija
Zdravlje i tehnologijaZdravlje i tehnologija
Zdravlje i tehnologija
Jelena Arsenovic
 
4. magelan
4. magelan4. magelan
4. magelan
saculatac
 
Безбедност на интернету
Безбедност на интернетуБезбедност на интернету
Безбедност на интернету
Goca Petrovic
 
Opasnosti na internetu
Opasnosti na internetuOpasnosti na internetu
Opasnosti na internetu
Pogled kroz prozor
 

What's hot (20)

Uspješna prezentacija u 8 koraka
Uspješna prezentacija u 8 korakaUspješna prezentacija u 8 koraka
Uspješna prezentacija u 8 koraka
 
Pubertet
PubertetPubertet
Pubertet
 
Bezbednost na internetu
Bezbednost na internetuBezbednost na internetu
Bezbednost na internetu
 
Hardverske komponente PC racunara
Hardverske komponente PC racunaraHardverske komponente PC racunara
Hardverske komponente PC racunara
 
Internet
InternetInternet
Internet
 
Михајло Пупин 2
Михајло Пупин 2Михајло Пупин 2
Михајло Пупин 2
 
398 dobre i loše strane interneta
398 dobre i loše strane interneta398 dobre i loše strane interneta
398 dobre i loše strane interneta
 
Bezbednost na internetu
Bezbednost na internetuBezbednost na internetu
Bezbednost na internetu
 
Upotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptx
Upotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptxUpotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptx
Upotreba savremenih informaciono komunikacionih tehnologija u nastavi.pptx
 
Obrazac za pravdanje izostanaka roditelji
Obrazac za pravdanje izostanaka   roditeljiObrazac za pravdanje izostanaka   roditelji
Obrazac za pravdanje izostanaka roditelji
 
Galileo Galilei
Galileo GalileiGalileo Galilei
Galileo Galilei
 
Osnovne komponente ikt uredjaja
Osnovne komponente ikt uredjajaOsnovne komponente ikt uredjaja
Osnovne komponente ikt uredjaja
 
Istorijski razvoj interneta
Istorijski razvoj internetaIstorijski razvoj interneta
Istorijski razvoj interneta
 
Raspad sfrj
Raspad sfrjRaspad sfrj
Raspad sfrj
 
Klima, biljni pokrov i ekološki problemi Hrvatske
Klima, biljni pokrov i ekološki problemi HrvatskeKlima, biljni pokrov i ekološki problemi Hrvatske
Klima, biljni pokrov i ekološki problemi Hrvatske
 
Finska
FinskaFinska
Finska
 
Zdravlje i tehnologija
Zdravlje i tehnologijaZdravlje i tehnologija
Zdravlje i tehnologija
 
4. magelan
4. magelan4. magelan
4. magelan
 
Безбедност на интернету
Безбедност на интернетуБезбедност на интернету
Безбедност на интернету
 
Opasnosti na internetu
Opasnosti na internetuOpasnosti na internetu
Opasnosti na internetu
 

Viewers also liked

покрытосеменные растения
покрытосеменные растенияпокрытосеменные растения
покрытосеменные растенияIrina Simonova
 
спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є.
спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є. спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є.
спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є. Irina Simonova
 
субъективизация по г
субъективизация по гсубъективизация по г
субъективизация по гIrina Simonova
 
пономаренко
пономаренкопономаренко
пономаренкоIrina Simonova
 
артпедагогика
артпедагогикаартпедагогика
артпедагогикаIrina Simonova
 
селекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.в
селекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.вселекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.в
селекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.вIrina Simonova
 
індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.
індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.
індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.Irina Simonova
 
Copvel ketinggian air_berbasis_sms
Copvel ketinggian air_berbasis_smsCopvel ketinggian air_berbasis_sms
Copvel ketinggian air_berbasis_sms19902
 
методи селекції рослин і тварин .учитель дзош 102 казмірук в.в
методи селекції рослин і тварин .учитель дзош 102 казмірук в.вметоди селекції рослин і тварин .учитель дзош 102 казмірук в.в
методи селекції рослин і тварин .учитель дзош 102 казмірук в.вIrina Simonova
 
Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)
Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)
Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)Amri Anwar
 
генотип як цілісна система. учитель дзош 117 черняховець о.о.
генотип як цілісна система. учитель дзош 117 черняховець о.о. генотип як цілісна система. учитель дзош 117 черняховець о.о.
генотип як цілісна система. учитель дзош 117 черняховець о.о. Irina Simonova
 
екологічні проблеми донбасу.учитель дзош 102 казмірук в.в
екологічні проблеми донбасу.учитель дзош 102 казмірук в.в екологічні проблеми донбасу.учитель дзош 102 казмірук в.в
екологічні проблеми донбасу.учитель дзош 102 казмірук в.в Irina Simonova
 
екологічні проблеми донбасу. дзош 102 робота учнів
екологічні проблеми донбасу. дзош 102 робота учнівекологічні проблеми донбасу. дзош 102 робота учнів
екологічні проблеми донбасу. дзош 102 робота учнівIrina Simonova
 
модифікаційна мінливість
модифікаційна мінливістьмодифікаційна мінливість
модифікаційна мінливістьIrina Simonova
 
критическое мышление (1)
критическое мышление (1)критическое мышление (1)
критическое мышление (1)Irina Simonova
 
Mat2 trigonometrija-sraga
Mat2 trigonometrija-sragaMat2 trigonometrija-sraga
Mat2 trigonometrija-sraga
Jadranko Tudović
 
Whatisrecycling 100405045415-phpapp02
Whatisrecycling 100405045415-phpapp02Whatisrecycling 100405045415-phpapp02
Whatisrecycling 100405045415-phpapp02Younes Alouani
 

Viewers also liked (19)

покрытосеменные растения
покрытосеменные растенияпокрытосеменные растения
покрытосеменные растения
 
спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є.
спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є. спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є.
спадкова мінливість. мутаційна мінливість. учитель дзош 57 гребьонкін а.є.
 
субъективизация по г
субъективизация по гсубъективизация по г
субъективизация по г
 
пономаренко
пономаренкопономаренко
пономаренко
 
артпедагогика
артпедагогикаартпедагогика
артпедагогика
 
селекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.в
селекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.вселекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.в
селекція мікроорганізмів. біотехнологія. учитель дзош 102 казмірук в.в
 
індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.
індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.
індивідуальний розвиток організмів. учитель дзош 102 казмірук в.в.
 
Copvel ketinggian air_berbasis_sms
Copvel ketinggian air_berbasis_smsCopvel ketinggian air_berbasis_sms
Copvel ketinggian air_berbasis_sms
 
методи селекції рослин і тварин .учитель дзош 102 казмірук в.в
методи селекції рослин і тварин .учитель дзош 102 казмірук в.вметоди селекції рослин і тварин .учитель дзош 102 казмірук в.в
методи селекції рослин і тварин .учитель дзош 102 казмірук в.в
 
мурмилова
мурмиловамурмилова
мурмилова
 
Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)
Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)
Undang undang no. 13 tahun 2003 tentang ketenagakerjaan (edit ppmi)
 
генотип як цілісна система. учитель дзош 117 черняховець о.о.
генотип як цілісна система. учитель дзош 117 черняховець о.о. генотип як цілісна система. учитель дзош 117 черняховець о.о.
генотип як цілісна система. учитель дзош 117 черняховець о.о.
 
екологічні проблеми донбасу.учитель дзош 102 казмірук в.в
екологічні проблеми донбасу.учитель дзош 102 казмірук в.в екологічні проблеми донбасу.учитель дзош 102 казмірук в.в
екологічні проблеми донбасу.учитель дзош 102 казмірук в.в
 
екологічні проблеми донбасу. дзош 102 робота учнів
екологічні проблеми донбасу. дзош 102 робота учнівекологічні проблеми донбасу. дзош 102 робота учнів
екологічні проблеми донбасу. дзош 102 робота учнів
 
модифікаційна мінливість
модифікаційна мінливістьмодифікаційна мінливість
модифікаційна мінливість
 
критическое мышление (1)
критическое мышление (1)критическое мышление (1)
критическое мышление (1)
 
мини сага
мини сагамини сага
мини сага
 
Mat2 trigonometrija-sraga
Mat2 trigonometrija-sragaMat2 trigonometrija-sraga
Mat2 trigonometrija-sraga
 
Whatisrecycling 100405045415-phpapp02
Whatisrecycling 100405045415-phpapp02Whatisrecycling 100405045415-phpapp02
Whatisrecycling 100405045415-phpapp02
 

Similar to Jt prg bg_igrafika_&_code_blocks_20121210

Manual smart notebook windows
Manual smart notebook windowsManual smart notebook windows
Manual smart notebook windows
ecoiote
 
Thematic_Mapping_Engine
Thematic_Mapping_EngineThematic_Mapping_Engine
Thematic_Mapping_Enginetutorialsruby
 
Thematic_Mapping_Engine
Thematic_Mapping_EngineThematic_Mapping_Engine
Thematic_Mapping_Enginetutorialsruby
 
Manual Civil 3d Ingles
Manual Civil 3d InglesManual Civil 3d Ingles
Manual Civil 3d Ingles
Ivan Martinez Saucedo
 
Microlearning Programs Calendar 2020
Microlearning Programs Calendar 2020Microlearning Programs Calendar 2020
Microlearning Programs Calendar 2020
Manisha Khetarpal
 
Dvdr77 17b Dfu Aen
Dvdr77 17b Dfu AenDvdr77 17b Dfu Aen
Dvdr77 17b Dfu Aenguest5e61fbf
 
[E Book] Linux, G C C X G C C The Gnu C C++ Language System For Emb...
[E Book]  Linux,  G C C  X G C C  The  Gnu  C  C++  Language  System For  Emb...[E Book]  Linux,  G C C  X G C C  The  Gnu  C  C++  Language  System For  Emb...
[E Book] Linux, G C C X G C C The Gnu C C++ Language System For Emb...Emanuele Bonanni
 
Java script tools guide cs6
Java script tools guide cs6Java script tools guide cs6
Java script tools guide cs6Sadiq Momin
 
인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼
HION IT
 
Protel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_designProtel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_design
emmansraj
 
Protel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_designProtel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_designhoat6061
 
Manual de RedPitaya
Manual de RedPitayaManual de RedPitaya
Manual de RedPitaya
Ruben Conde
 
Encodo c# handbook_1_5_2
Encodo c# handbook_1_5_2Encodo c# handbook_1_5_2
Encodo c# handbook_1_5_2Centre D'appel
 
Flash File Format Specification
Flash File Format SpecificationFlash File Format Specification
Flash File Format Specificationguest0ebe1e
 
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
HION IT
 
Test and target book
Test and target bookTest and target book
Test and target bookMesurex
 
Vegal tk11
Vegal tk11Vegal tk11
Vegal tk11Klik111
 

Similar to Jt prg bg_igrafika_&_code_blocks_20121210 (20)

Manual smart notebook windows
Manual smart notebook windowsManual smart notebook windows
Manual smart notebook windows
 
Thematic_Mapping_Engine
Thematic_Mapping_EngineThematic_Mapping_Engine
Thematic_Mapping_Engine
 
Thematic_Mapping_Engine
Thematic_Mapping_EngineThematic_Mapping_Engine
Thematic_Mapping_Engine
 
Manual Civil 3d Ingles
Manual Civil 3d InglesManual Civil 3d Ingles
Manual Civil 3d Ingles
 
Microlearning Programs Calendar 2020
Microlearning Programs Calendar 2020Microlearning Programs Calendar 2020
Microlearning Programs Calendar 2020
 
Dvdr77 17b Dfu Aen
Dvdr77 17b Dfu AenDvdr77 17b Dfu Aen
Dvdr77 17b Dfu Aen
 
[E Book] Linux, G C C X G C C The Gnu C C++ Language System For Emb...
[E Book]  Linux,  G C C  X G C C  The  Gnu  C  C++  Language  System For  Emb...[E Book]  Linux,  G C C  X G C C  The  Gnu  C  C++  Language  System For  Emb...
[E Book] Linux, G C C X G C C The Gnu C C++ Language System For Emb...
 
Java script tools guide cs6
Java script tools guide cs6Java script tools guide cs6
Java script tools guide cs6
 
인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB22 PB32 감열 모바일프린터 매뉴얼
 
Protel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_designProtel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_design
 
Protel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_designProtel 99 se_traning_manual_pcb_design
Protel 99 se_traning_manual_pcb_design
 
Step by step power point 2007
Step by step power point 2007Step by step power point 2007
Step by step power point 2007
 
Kayode Olusoji Module 6-Final Task
Kayode Olusoji Module 6-Final TaskKayode Olusoji Module 6-Final Task
Kayode Olusoji Module 6-Final Task
 
Manual de RedPitaya
Manual de RedPitayaManual de RedPitaya
Manual de RedPitaya
 
Encodo c# handbook_1_5_2
Encodo c# handbook_1_5_2Encodo c# handbook_1_5_2
Encodo c# handbook_1_5_2
 
Ebay News 1998 10 27 Earnings
Ebay News 1998 10 27 EarningsEbay News 1998 10 27 Earnings
Ebay News 1998 10 27 Earnings
 
Flash File Format Specification
Flash File Format SpecificationFlash File Format Specification
Flash File Format Specification
 
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
 
Test and target book
Test and target bookTest and target book
Test and target book
 
Vegal tk11
Vegal tk11Vegal tk11
Vegal tk11
 

Recently uploaded

Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 

Recently uploaded (20)

Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 

Jt prg bg_igrafika_&_code_blocks_20121210

  • 1. Programirajmo grafiku uz stari, dobri BGI... Knjiga I.: BGI & CodeBlocks U ovom priručniku autor je prikupio s raznih strana na internetu vrijednu kolekciju materijala o oživljavanju Borland Graphics Interface-a u Code::Blocks-u, modernom sučelju za programiranje u C i C++ jezicima. Dani su i konkretni primjeri elementarne grafike za školske potrebe. Jadranko Tudović (2010) ISI - Prva srednja informatička škola sp.j.
  • 2. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 2 ISI-Prvasrednjainformatičkaškolasp.j. SADRŽAJ: PREDGOVOR........................................................................................................................................ 5 OSNOVE RAČUNALNE GRAFIKE........................................................................................................... 6 ALATI ZA PROGRAMIRANJE u C jeziku................................................................................................. 6 Instalacija grafičke biblioteke u Code::Blocks ..................................................................................... 9 Bug u BGIgraphics.h (tj. winbgim.h).................................................................................................. 10 Što još treba ispraviti?....................................................................................................................... 11 Kako koristiti biblioteku libbgix.a? .................................................................................................... 11 Moj prvi program s grafikom............................................................................................................. 12 PROBLEMI?........................................................................................................................................ 13 Pregled češće korištenih naredbi BGI grafike................................................................................... 14 Primjeri programiranja grafike.......................................................................................................... 16 BGI_PRIMJER_01: Crtanje linije................................................................................................. 16 BGI_PRIMJER_02: Crtanje kvadrata .......................................................................................... 16 BGI_PRIMJER_03: Crtanje kružnice žute boje........................................................................... 16 BGI_PRIMJER_04: Crtanje ELIPSE žute boje .............................................................................. 16 BGI_PRIMJER_04: Crtanje TROKUTA žute boje......................................................................... 17 Biblioteka rutina za programiranje miša........................................................................................... 18 Funkcije za programiranje miša..................................................................................................... 19 Primjer programiranja miša s ismouseclick i getmouseclick funkcijama..................... 20 Primjer rutine za miša s rukovateljem (eng. mouse handler) ....................................................... 20 PRIMJER: Unos koordinata poligona mišem ............................................................................. 21 Grafičke rutine u BGI biblioteci ......................................................................................................... 22 Inicijalizacija grafike:...................................................................................................................... 22 BOJE u Winbgim ............................................................................................................................ 22 RGB boje........................................................................................................................................ 22 Upravljanje ulaza preko TIPKOVNICE ................................................................................................ 23 Napredne grafičke naredbe u BGI biblioteci ..................................................................................... 23 Podrška za dvostruko baferiranje (Double-Buffering)................................................................... 23 Podrška za ispis na grafički prozor................................................................................................. 23 Podrška za štampanje, učitavanje i zapisivanje grafike................................................................. 23 Podrška za višestruke prozore....................................................................................................... 24 Ostala dokumentacija za proučavanje BGI grafike........................................................................ 24 Kako ukloniti konzolni (tzv. DOS) prozor? .................................................................................... 24 Borland Graphics Interface (BGI) for Windows................................................................................. 25
  • 3. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 3 ISI-Prvasrednjainformatičkaškolasp.j. FUNKCIJE: ...................................................................................................................................... 25 Koje su to naredbe u winbgim.h?.................................................................................................. 27 CRTAJUĆE funkcije (eng. Drawing Functions)............................................................................ 27 RAZNE funkcije (eng. Miscellaneous Functions) ....................................................................... 27 "PROZORSKE" funkcije (eng. Window Creation / Graphics Manipulation)............................... 28 Interakcija s korisnikom (eng. User Interaction) ....................................................................... 28 User-Controlled Window Functions (winbgi.cpp) ..................................................................... 28 Double buffering support (winbgi.cpp)..................................................................................... 28 "SLIKOVNE" funkcije (rasterska grafika) (eng. Image Functions (drawing.cpp))....................... 29 TEKSTNE iliti "PISAJUĆE" funkcije (eng. Text Functions (text.cpp))........................................... 29 "MIŠJE" funkcije (eng. Mouse Functions (mouse.cpp))............................................................. 29 Upravljanje paletama boja (eng. Palette Functions)................................................................. 29 FUNKCIJE, još jednom.................................................................................................................... 30 Drawing Functions..................................................................................................................... 30 Miscellaneous Functions ........................................................................................................... 30 Window Creation / Graphics Manipulation .............................................................................. 31 User Interaction......................................................................................................................... 31 User-Controlled Window Functions (winbgi.cpp) ..................................................................... 31 Double buffering support (winbgi.cpp)..................................................................................... 31 Image Functions (drawing.cpp)................................................................................................. 31 Text Functions (text.cpp)........................................................................................................... 32 Mouse Functions (mouse.cpp).................................................................................................. 32 Palette Functions....................................................................................................................... 32 Color Macros ............................................................................................................................. 32 Napredno korištenje BGI grafike....................................................................................................... 33 initwindow..................................................................................................................................... 33 setcurrentwindow ......................................................................................................................... 34 getcurrentwindow......................................................................................................................... 34 closegraph ..................................................................................................................................... 35 swapbuffers................................................................................................................................... 36 getactivepage ................................................................................................................................ 36 getvisualpage................................................................................................................................. 37 setactivepage................................................................................................................................. 37 setvisualpage................................................................................................................................. 38 setviewport.................................................................................................................................... 39 clearviewport................................................................................................................................. 40
  • 4. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 4 ISI-Prvasrednjainformatičkaškolasp.j. getx................................................................................................................................................ 41 gety................................................................................................................................................ 42 moveto .......................................................................................................................................... 43 moverel.......................................................................................................................................... 44 getmaxx ......................................................................................................................................... 45 getwindowwidth............................................................................................................................ 46 getwindowheight........................................................................................................................... 46 setcolor.......................................................................................................................................... 47 setbkcolor...................................................................................................................................... 49 getch.............................................................................................................................................. 50 kbhit............................................................................................................................................... 52 KONSTANTIN KNIZNIK ....................................................................................................................... 54
  • 5. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 5 ISI-Prvasrednjainformatičkaškolasp.j. PREDGOVOR
  • 6. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 6 ISI-Prvasrednjainformatičkaškolasp.j. OSNOVE RAČUNALNE GRAFIKE Uporaba računala uz primjenu grafike daje korisniku puno više informacija od pukog računanja brojki i premetanja slova. Međutim, grafika u računalima klase "IBM-PC" – koja su građena na principima otvorene hardverske arhitekture (što pak znači da korisnik može imati bilo kakav grafički podsustav u svom računalu) rezultirala je otežanim pristupom grafičkim resursima računala. Naime, grafičkim mogućnostima računala upravlja operacijski sustav računala (skraćeno OS). Svi zahtijevi za grafikom idu strogo preko "njega" (> OS-a). Stoga, da bi naše programiranje računala uz primjenu grafike uopće "prošlo" – jednostavno moramo dodati biblioteke (eng. library) s novim, grafičkim naredbama (najčešće funkcijama) . Tek tada će biti moguće na jednostavan način otvarati grafički prozor u kojega se može usmjeriti izlaz iz našeg programa. Recimo samo i ovu zanimljivu činjenicu – pisanje slova u grafičkom prozoru postaje crtanje slova, jer tu više ne prolaze iste naredbe kao u konzolnom (onom tekstualnom) prozoru. Dobar link o Dev-C++ & Graphics http://www.onecore.net/dev-c-graphics.htm Što je WinBGIm - WinBGIm is a basic graphics drawing package that emulates one of the most successful graphics libraries of all times, the Borland Graphics Interface (BGI). WinBGIm adds some extra facilities, like the possibility of catching mouse clicks and mouse position. The success of BGI was due to its simplicity. The code of graphical programs produced with WinBGIm is very simple, compared to that of other graphics packages. ALATI ZA PROGRAMIRANJE u C jeziku Programiranje računala je vještina koja se obavlja uz uporabu određenih programskih alata. Ako gledamo po dijelovima priču o programiranju – tada bi mogli zaključiti da nam je glavni alat neki prevodilac ili u žargonu kompajler (od eng. compiler), pa zatim neki editor teksta (u Windows okolini u najmanju ruku spartanski Notepad.exe, no šalu na stranu – puno bolje: Notepad++), pa zatim neki program koji će povezati datoteke... dakle linker.exe itd.... Na raspolaganju imamo razne kompajlere:  MinGW 2.95/3.x/4.x/5.0  Cygwin  Borland C++ Compiler  Microsoft C++ Compiler  Intel C++ Compiler  Lcc-Win32  Open Watcom C/C++  Digital Mars C/C++  Ch Interpreter  Pelles C Sve to puno bolje od pojedinih dijelova iz gornje priče nalazi se u cjelovitim, objedinjenim ili integriranim sustavima – skraćenica na engleskom jeziku za takve sustave je IDE. IDE dolazi od Integrated Development Environment, dakle integrirana razvojna okolina ili sučelje
  • 7. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 7 ISI-Prvasrednjainformatičkaškolasp.j. Za potrebe programiranja u C odnosno C/C++ jeziku imamo na raspolaganju desetine sustava. Evo nekoliko njih koji mi padaju na pamet: NAZIV Licenca Win Lin Mac Specifično NAPOMENA 1 BloodShed Dev- C++ GPL zadnja verzija: 02-2005! Više se ne održava! 2 CodeLite GPL 3 Code::Blocks GPL 4 Pelles C Free Windows CE Pravi, "čistokrvni" C prevodilac i razvojna okolina. Redovito održavan. Najnoviji C standardi (C11)!!! 5 C-Free Comerc. 6 NetBeans Free 7 Eclipse Free 8 Visual C++ 2010 Express Edition Free 9 KDevelop GPL *ima ih puno više... Code::Blocks Code::Blocks je besplatno C/C++ integrirano razvojno sučelje, IDE, napravljeno po najvišim zahtjevima korisnika. Dizajnirano je kao potpuno proširiva i prilagodljiva (konfigurabilna) radna okolina za potrebe programiranja. Kompajleri koje trenutno podržava Code::Blocks:  GNU GCC (incl. G77) (Linux)  MinGW GCC (incl. G77) (Win32)  MSP430 GCC (Win32, Linux, BSD)  TriCore GCC (Win32, Linux)  PowerPC GCC (Win32, Linux)  Apple GCC (Xcode) (Mac OS X)  Microsoft Visual C++ Toolkit 2003 (Win32)  Microsoft Visual C++ 2005 (Win32)  LCC (Win32)  Borland's C++ Compiler 5.5 (Win32)  DigitalMars C/C++ (Win32)  OpenWatcom (Win32)  Intel C++ compiler (Win32)  Small Device C Compiler (SDCC)  Digital Mars D  GDC D Compiler  LLVM D Compiler *prema: http://wiki.codeblocks.org/index.php?title=Main_Page Borland BGI Graphics Zahvaljujući vrijednom radu ruskog matematičara i računalnog znastvenika Konstantina Knizhnika, kao i Marku Richardsonu i Michaelu Mainu iz Sveučilišta Coloradu (University of Colorado), te zadnjim modifikacijama Adriana Sandora (modifications by Adrian Sandor) raspolažemo s četiri fantastične datoteke koje nam omogućuju uporabu grafičkih naredaba koje je izvorno tvrtka Borland uključila u njihovo klasično integrirano sučelje za razvoj Turbo C++ aplikacija. To su sljedeća četiri fajla, komprimirana u winbgim_devcpp4990_20041220.zip: 1. winbgim.h (kopirati u C:Program FilesCodeBlocksMinGWinclude) 2. conio.h (kopirati u C:Program FilesCodeBlocksMinGWinclude) 3. libbgi.a (kopirati u C:Program FilesCodeBlocksMinGWlib)
  • 8. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 8 ISI-Prvasrednjainformatičkaškolasp.j. 4. libconio.a (kopirati u C:Program FilesCodeBlocksMinGWlib) VAŽNA NAPOMENA: Pretraživanjem interneta naći ćete više izvora za skidanje navedenih datoteka. Međutim, one nisu iste po mogućnostima. Nakon testiranja više njih odlučio sam se za download sa stranice: http://www.uniqueness-template.com/devcpp. Istina sve je navedeno za uporabu u Dev-C++ razvojnoj okolini, što ovog trena slobodno zanemarite!
  • 9. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 9 ISI-Prvasrednjainformatičkaškolasp.j. Slika 1 - izbornik Settings Slika 2 – Linker settings Instalacija grafičke biblioteke u Code::Blocks U programsku razvojnu okolinu Code::Blocks jednostavnu 2D grafiku, razvijenu pred 25 godina u Borlandu, jednoj od najpoznatijih softverskih tvrtki, uključujemo na sljedeći način: 0. korak: napraviti download 2 datoteke s adrese: PROMIJENITI OVAJ DIO – staviti fajlove na naš server/portal na eng. i hrv. te komentirati  http://www.uniqueness-template.com/devcpp/graphics.h  http://www.uniqueness-template.com/devcpp/libbgi.a 1. korak: u folder include kopirati datoteku: BGIgraphics.h 2. korak: u folder lib kopirati datoteku: libbgix. 3. korak: Nakon toga potrebno je prijaviti korištenje navedene biblioteke spuštanjem izbornika Settings ->Compiler and debugger otvorimo karticu (tab) Linker utipkamo u Other linker settings: -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32
  • 10. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 10 ISI-Prvasrednjainformatičkaškolasp.j. Bug u BGIgraphics.h (tj. winbgim.h) Upavo smo otkrili čudnovati bug u header-fajlu BGIgraphics.h (izvorno: winbgim.h). Sasvim slučajno, ustanovljavajući zašto BGI grafika radi na mom računalu dok isti krajnje jednostavni primjer ne želi proraditi – dapače, uporno javlja grešku koju sam stalno ignorirao dok nisam shvatio da je to istinita poruka od kompajlera... Nekim čudom, meni je implementacija BGI grafike proradila glatko na Code::Blocks-u. Prvobitno sam imao Code::Blocks 8.6 (ili tako nekako) i nedavno sam ga "zgazio" verzijom 10.5. Istina, javljao je neke poruke koje sam zanemario. Glavno mi je bilo da stvar radi! Dapače, radila je i BGI grafika po logici ugradnje u Dev-C++ (stavi winbgim.h u include-folder i lbgi.a u lib-folder i pazi ovo, sve što radiš, započni kao C++ a ne kao C projekt!!!). Sve mi je radilo. Onda sam odlučio sve to instalirati na školska računala. Super. Skinuli smo MingW varijantu, ugradili moju varijantu BGI fajlova (moju samo po preimenavanju, jer ništa nisam prekodirao) – i idemo testirati. Program za test je krajnje jednostavan: #include <BGIgraphics.h> int main() { int x1,y1,x2,y2,x3,y3; //otvori graficki prozor velicine 400x300 pixela initwindow(400,300,"Crtamo TROKUT"); x1=200; y1=50; x2=120; y2=190; x3=280; y3=210; line(x1,y1,x2,y2); line(x2,y2,x3,y3); line(x3,y3,x1,y1); getch(); closegraph(); } Međutim, neće raditi!!! Uporno javlja grešku: ...i stvarno, u header-fajlu BGIgraphics.h potkrala se greška na liniji 302. Ta greška zasmetala je tek novoj verziji MingW kompajlera! Stoga sam tu grešku ispravio i sada sve radi! Naime na liniji 302 u BGIgraphics.h (bivše ime: winbgim.h) pogrešno je dva puta uzastopce navedena integerska varijabla right. U drugom navodu int right promijenjen je u int top =... i tako je ispravljena ova greška. void printimage( const char* title=NULL, double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75, int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX,
  • 11. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 11 ISI-Prvasrednjainformatičkaškolasp.j. bool active=true, HWND hwnd=NULL ); Što još treba ispraviti? Detalj koji nervira ali definitivno nije bug je problem sa utipkavanjem desne uglate zagrade ("]") u CB- u. Tu pak treba promijeniti postavku koja je prilično duboko skrivena u opciji Settings : Settings-> Editor -> Keyword Shortcuts -> Search -> Go to function -> u desnom prozoru tekst: Ctrl Shift G ili zamijeniti ili obrisati. Kako koristiti biblioteku libbgix.a? Programska biblioteka libbgix.a je tzv. objektna datoteka koja sadrži binarni zapis kompiliranih naredbi za rad s elementarnom grafikom. Popis tih naredbi je vidljiv iz header datoteke BGIgraphics.h koja "inkludira" sve te grafičke naredbe. Iz praktičnih razloga ali i zbrke na internetu odlučio sam preimeovati te dvije datoteke: winbgim.h BGIgraphics.h libbgi.a libbgix.a Glavni razlog je to što na internetu postoje tri-četiri verzije koje nisu iste. Nakon što sam to istražio odabrao sam najbolju verziju i dao joj novo ime. Dobro je znati da biblioteka BGIgraphics.h automatski uključuje sljedeće tri biblioteke: #include <stddef.h> #include <conio.h> #include <windows.h>
  • 12. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 12 ISI-Prvasrednjainformatičkaškolasp.j. Moj prvi program s grafikom... Nakon pokretanja Code::Bocks-a, započnimo ovaj zadatakakreiranjem nove datoteke na sljedeći način: csN(to je: File > New > Empty File) Zatim utipkajmo sljedeći programski tekst u editor: ... i pohranimo ga naredbom Save As u odabranu mapu uz obavezno pisanje ekstenzije datoteke kao .cpp !!! Još jednom: OBAVEZNO NAPISATI .cpp inače ništa od grafike!!! Tipkom 9 pokrenemo Build & Run i dobijemo grafički prozor veličine 400x300 piksela u čijem središtu je nacrtana kružnica radijusa 50 piksela, žute boje!!! Probajte!!! #include <BGIgraphics.h> int x=400, y=300; //deklaracija varijabli za širinu i visinu garfičkog prozora int main() { initwindow(x,y,"Kruznica..."); //otvori grafički prozor veličine 400 X 300 piksela setcolor (14); // postavimo boju = 14 --> žuta! circle(x/2,y/2,50); // crtaj kružnicu u središtu prozora radiusa 50 piksela while(!kbhit()); //čekaj dok korisnik ne pritisne bilo koju tipku na tipkovnici closegraph(); //zatvori grafički prozor return 0; }
  • 13. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 13 ISI-Prvasrednjainformatičkaškolasp.j. PROBLEMI? ....Ali ja sam dobio sljedeće greške nakon pritiska na tipku F9: Ništa zato, to samo znači da nisi odradio korak br. 3. Sretno! i uz puno strpljenja!!! Vaš profesor, Jadranko Tudović
  • 14. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 14 ISI-Prvasrednjainformatičkaškolasp.j. Pregled češće korištenih naredbi BGI grafike Radnja Sintaksa objašnjenje otvaranje grafičkog prozora initwindow (wx,wy) ili initwindow (wx,wy,"NASLOV")ili initwindow (wx,wy,"nas",xo,yo) otvara grafički prozor širine wx piksela i visine wy piksela, a ako se navedu xo i yo koordinate – tada je to početak gronjeg lijevog ugla prozora dok je "Naslov" naziv grafičkog prozora. zatvaranje grafičkg prozora closegraph(); uvijek zadnja naredba u slijedu izvršavanja grafičkih naredbi.NAPOMENA – prije toga aktivirati npr. getch(); brisanje grafičkog prozora cleardevice(); briše sve nacrtano na postojećem grafičkom prozoru (tako da graf. prozor ispuni bojom podloge) i postavlja kursor na "home position" – 0,0. Pomak pozicije crtanja (bez traga) moveto(x,y); pomiče pokazivač u točku s koordinatama (x,y) moverel(dx,dy); pomiče pokazivač za dx u smjeru osi x i za dy u smjeru osi y crtanje točke putpixel(x,y,boja); crta točku s koordinatama (x,y) zadane boje getx(); vraća poziciju koordinate x gety(); vraća poziciju koordinate y crtanje linija line (x1,y1,x2,y2); Povlači liniju od točke (x1,y1) do točke (x2,y2) linerel(dx,dy); Crta liniju od trenutnog položaja pokazivača do točke koja je za dx udaljena po x-osi, a za dy po y-osi lineto (x,y); Crta liniju od trenutnog položaja pokazivača do točke s koordinatama (x,y) setlinestyle(x,1,1); stil linije (0-puna crta, 1-točkasta, 2- iscrtkana, 3-deblja točkasta, 4-točkasta s većim razmakom, 5-debela crta boja podloge setbkcolor(x); određuje boju podloge prozora (0 -15) boja linije ili teksta setcolor(x); određuje boju linija (0 -15) pravokutnik i kvadar rectangle(x1,y1,x2,y2); Pravokutnik kojemu su (x1,y1) koordinate gornjeg lijevog, a (x2,y2) donjeg desnog vrha bar(x1,y1,x2,y2); Pravokutnik ispunjen trenutnom bojom i trenutnim stilom bar3d(x1,y1,x2,y2,dubina,oznaka); Trodimenzionalni pravokutnik (kvadar). Dubinom određujemo trodimenzionalnost. Za najbolji dojam trodimenzionalnosti preporučuje se uzeti 25% širine pravokutnika (x2-x1)/4. Posljednja oznaka određuje da li je lik zatvoren (1) ili otvoren (0) kružnica circle(x,y,r); kružnica polumjera r sa središtem u točki (x,y)
  • 15. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 15 ISI-Prvasrednjainformatičkaškolasp.j. kružni luk arc(x,y,pocetak,kraj,r); dio kružnice sa središtem u točki (x,y) polumjera r od mjesta pocetak (u stupnjevima) do mjesta kraj isječak pieslice(x,y,pocetak,kraj,r); popunjen dio kruga od mjesta pocetak do mjesta kraj elipsa ellipse(x,y,pocetak,kraj,a,b); elipsa sa središtem u točki(x,y) od mjesta početak (u stupnjevima) do mjesta kraj, duljine velike osi a, a male osi b fillellipse(x,y,a,b) popunjena elipsa sector(x,y,pocetak,kraj,a,b); popunjen dio elipse ispis teksta outtext(string); ispisuje tekst u grafičkom prozoru počevši od vrha prozora outtextxy(x,y,string); ispisuje tekstualni string s početkom na koordinati x,y settextstyle(oblik,smjer,vel); postavke stila teksta: int oblik, vrijednosti: 0 do 10 int smjer, vrijednosti 0 do 2 gdje je HORIZ_DIR = 0 VERT_DIR = 1 -VERT_DIR = 2 int vel, veličina slova (0,1,2,3...)
  • 16. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 16 ISI-Prvasrednjainformatičkaškolasp.j. Primjeri programiranja grafike BGI_PRIMJER_01: Crtanje linije //BGI_PRIMJER_01: Crtanje linije #include <BGIgraphics.h> int main() { initwindow(400,300); //otvaranje grafičkog prozora 400x300 pixela moveto(0,0); //pozicioniraj pero na 0,0 (gornji lijevi ugao) lineto(50,50); //povuci liniju do točke 50,50 while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku //tipku closegraph(); //zatvori grafički prozor return 0; } BGI_PRIMJER_02: Crtanje kvadrata //BGI_PRIMJER_02: Crtanje kvadrata #include <BGIgraphics.h> int main() { initwindow(400,300); //otvaranje grafičkog prozora 400x300 pixela moveto(20,20); lineto(20,50); lineto(50,50); lineto(50,20); lineto(20,20); while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku //tipku closegraph(); //zatvori grafički prozor return 0; } BGI_PRIMJER_03: Crtanje kružnice žute boje //BGI_PRIMJER_03: Crtanje kružnice žute boje #include <BGIgraphics.h> int main() { initwindow(400,400); //otvaranje grafičkog prozora 400x400 pixela setcolor(14); //postavi boju pera na 14 (=žuto) circle(200,200,50); //kružnica radiusa 50 na koord. 200,200 while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku //tipku closegraph(); //zatvori grafički prozor return 0; } BGI_PRIMJER_04: Crtanje ELIPSE žute boje //BGI_PRIMJER_04: Crtanje ELIPSE žute boje #include <BGIgraphics.h> int main() { initwindow(400,400); //otvaranje grafičkog prozora 400x400 pixela setcolor(14); //postavi boju pera na 14 (=žuto) int xo = 200; //x-koord. središta elipse int yo = 200; //y-koord. središta elipse int fip= 0; //početni kut fi inf fik= 360; //krajnji kut fi int rx = 100; //radius po x osi int ry = 50; //radius po y osi ellipse(xo,yo,fip,fik,rx,ry); while(!kbhit()); //zaustavi program dok korisnik ne pritisne neku //tipku closegraph(); //zatvori grafički prozor return 0; }
  • 17. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 17 ISI-Prvasrednjainformatičkaškolasp.j. BGI_PRIMJER_04: Crtanje TROKUTA žute boje //BGI_PRIMJER_04: Crtanje TROKUTA žute boje #include <BGIgraphics.h> int main() { int x1,y1,x2,y2,x3,y3; //otvori grafički prozora 400x300 pixela s nazivom "Crtamo TROKUT" initwindow(400,300,"Crtamo TROKUT"); x1=200; y1=50; x2=120; y2=190; x3=280; y3=210; line(x1,y1,x2,y2); line(x2,y2,x3,y3); line(x3,y3,x1,y1); getch(); closegraph(); }
  • 18. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 18 ISI-Prvasrednjainformatičkaškolasp.j. Biblioteka rutina za programiranje miša. Tri su rutine glavne za programiranje miša:  int mousex( ) int mousey( ) vraćaju trenutne x i y koordinate miša u grafičkom prozoru. Ako miš još nije bio u grafičkom prozoru tada su obje koordinate jednake nuli. U situaciji kad je miš već bio u grafičkom prozoru ali je izašao van na bilo kojoj strani prozora tada su vrijednosti koordinata jednake zadnjoj poznatoj poziciji miša neposredno pred izlazak iz prozora.  bool ismouseclick(kind) Ova funkcija vraća vrijednost true ako je NEizvršen specificirani događaj. Argumenti funkcije ismouseclick su konstante sadržane u winbgim.h datoteci: WM_MOUSEMOVE ....... detekcija pomaka miša WM_LBUTTONDBLCLK ... detekcija lijevog dvo-klika WM_LBUTTONDOWN ..... detekcija pritska lijeve tipke miša WM_LBUTTONUP ....... detekcija otpuštanja lijeve tipke miša WM_MBUTTONDBLCLK ... detekcija dvo-klika srednje tipke (ili kotačića) WM_MBUTTONDOWN ..... detekcija pritiska srednje tipke (kotačića) miša WM_MBUTTONUP ....... detekcija otpuštanja srednje tipke (kotačića) miša WM_RBUTTONDBLCLK ... detekcija desnog dv-klika WM_RBUTTONDOWN ..... detekcija pritiska desne tipke miša WM_RBUTTONUP ....... detekcija otpuštanja desne tipke miša [Opaska autora rutina za miša: Rukovatelji srednje tipke miša nisu radili na mom računalu. Nažalost, još nisam stigao otkriti razlog – moguće i neispravan miš ili pak bug u mom programu...] E, sad, malo "filozofije"... Programiranje miša, tipkovnice i ostalih uređaja "prikopčanih" na računalo spada pojmovno u tzv. "event-driven programming" – dakle, programiranje događaja (eventa). Radnje koje radimo s mišem su za računalo nekakvi "događaji" pa stoga događaje koje proizvodimo mišem (eng. mouse event) možemo obrađivati (ili slobodno rečeno hvatati) pozivanjem funkcije getmouseclick (koja nam daje, očitava koordinate događaja – poziciju miša u pixelima), ili pozivanjem funkcije clearmouseclick (koja obrađuje određeni događaj (ili radnju) s mišem bez dostavljanja koordinata). Pogledajmo detaljniji opis tih funkcija u nastavku priče. void getmouseclick(kind, int& xint& y) This function sets x and y to the pixel coordinates of an unprocessed event of the specified kind. If there is no such event, then the function sets both x and y to -1. The value of the argument kind may be any of the constants listed above. After callinggetmouseclick, for a particular kind of event, the ismouseclick will return false for that kind of event until another such event occurs. void clearmouseclick(kind) This is just like getmouseclick, except it does not provide the x and y coordinates of the event. The value of the argument kind may be any of the constants listed above. After calling clearmouseclick, for a particular kind of event, the ismouseclick will return false for that kind of event until another such event occurs. void registermousehandler(kind, h) Most mouse processing can be carried out with the ismouseclick and getmouseclick. But sometimes you need more control. In general, you can obtain more control by writing a different "handler function" to handle each different kind of mouse event, and you "register" each of your handlers by calling registermousehandler. The first argument to registermousehandler is one of the constants listed above. The second argument to registermousehandler must be the name of the handler function that you wrote. This function must be a void function with two int parameters. Whenever the specified mouse event occurs, your handler will be called and the two int parameters will be the x and y positions where the event happened.
  • 19. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 19 ISI-Prvasrednjainformatičkaškolasp.j. Funkcije za programiranje miša Sljedeći niz naredaba služi za precizno "hvatanje" radnji s mišem odnosno njihovo "čišćenj" iz priručne memorije (buffera). Funkcije ZA PROGRAMIRANJE MIŠA Pozicija miša mousex() x-koordinata miša (u pixelima, naravno) mousey() y-koordinata miša Pomak ismouseclick(WM_MOUSEMOVE) "hvatanje" pomicanja miša clearmousclick(WM_MOUSEMOVE) Brisanje iz pomaka iz buffera Pritisnuta LIJEVA tipka ismouseclick(WM_LBUTTONDOWN) Lijeva tipka miša pritisnuta (i držimo ju) clearmousclick(WM_LBUTTONDOWN) ismouseclick(WM_LBUTTONDOWN) LIJEVI DVOklik clearmousclick(WM_LBUTTONDBCLICK) ismouseclick(WM_LBUTTONDBCLICK) Dvoklik LIJEVOM tipkom miša Pritisnuta DESNA tipka clearmousclick (WM_RBUTTONDOWN) ismouseclick (WM_RBUTTONDOWN) Desna tipka pritisnuta (i držimo ju) DESNI DVOklik ismouseclick(WM_RBUTTONDBCLICK) Dvoklik DESNOM tipkom miša clearmousclick (WM_RBUTTONDBCLICK) Pritisnuta SREDNJA t. clearmousclick (WM_MBUTTONDOWN) ismouseclick (WM_MBUTTONDOWN) SREDNJA tipka pritisnuta i zadržana SREDNJI DVOklik ismouseclick(WM_ MBUTTONDBCLICK) Dvoklik SREDNJOM tipkom miša clearmousclick (WM_MBUTTONDBCLICK)
  • 20. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 20 ISI-Prvasrednjainformatičkaškolasp.j. Primjer programiranja miša s ismouseclick i getmouseclick funkcijama Pretpostavimo da želite programirati zaustavljanje izvođenja programa koje biva prekinuto klikom na lijevu tipku miša (eng. "wait for a left mouse click"). Nakon toga program će ispisati zadnje x,y koordinate na kojima je miš bio u grafičkom prozoru. Pogledajmo funkciju koja obavlja takav zadatak: void cekaj_lijevi_klik( ) { const int DELAY = 50; // milisekunde zadrške prije provjere int x, y; while (!ismouseclick(WM_LBUTTONDOWN)) delay(DELAY); getmouseclick(WM_LBUTTONDOWN, x, y); cout << "Najzadnji lijevi klik na: " << x << " " << y << endl; } Primjer rutine za miša s rukovateljem (eng. mouse handler) Pretpostavimo da želite ispisati poruku s x i y koordinatama pozicije miša kad god je kliknuta desna tipka miša. Tada ćete početi s pisanjem handler funkcije poput ove: void moj_desnokliki_handler(int x, int y) { cout << "Desni klik miša na: " << x << " and " << y << endl; } E, sada negdje u svom programu (nakon što ste inicijalizirali grafički prozor), morate registrirati ovaj fini handler naredbom: registermousehandler(WM_RBUTTONDOWN, my_right_click_handler); U pravilu posao koji obavlja handler mora biti što kraći. Ako trebate izvršiti puno posla, mijenjajte handlerom neku globalnu varijablu koja će kasnije biti okidač tog većeg posla (u pravilu nekog duljeg programskog koda)! Na taj način će handler promptno odgovarati (vraćati će se brzo).
  • 21. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 21 ISI-Prvasrednjainformatičkaškolasp.j. PRIMJER: Unos koordinata poligona mišem ...uz istovremeno crtanje tog poligona. Svaki vrh poligona ujedno je iscrtan malom kružnicom uz koju se ispisuje i redni broj točke poligona: #include <stdio.h> #include <winbgim.h> #define CRVENA 4 #define BIJELA 15 #define ZELENA 2 int main() { int cnt=0; int x, y int X[50], Y[50]; char brt[2]; initwindow(400,300); //otvori graficki prozor velicine 400x300 pixela setbkcolor(BIJELA); //boja podloge neka bude BIJELA cleardevice(); //obriši prozor while (!kbhit()) //vrti petlju sve dok korisnik ne pritisne neku tipku tipkovnice { if (ismouseclick(WM_LBUTTONDOWN)) //...ako je LIJEVI klik napravljen tada { cnt++; //povećaj varijablu cnt za 1 X[cnt]=mousex(); //spremi x-koord. miša u polje X[cnt] Y[cnt]=mousey(); //spremi y-koord. miša u polje Y[cnt] setcolor(CRVENA); //postavi crvenu boju pera circle(X[cnt],Y[cnt],3); //nacrtaj malu crvenu kružnicu na koord. točke sprintf(brt,"%d",cnt); //zapiši brojač cnt kao tekst u varijablu brt outtextxy(X[cnt],Y[cnt],brt); //ispiši u graf. prozor broj točke -> brt setcolor(ZELENA); //promjena boje pera u ZELENU if (cnt>1) line(X[cnt-1],Y[cnt-1],X[cnt],Y[cnt]); //crtaj spojnice tek kad je 2. točka klknuta... clearmouseclick(WM_LBUTTONDOWN); //OBAVEZNO!!! poništi događaj LBUTTON... } if (ismouseclick(WM_RBUTTONDOWN)) //ako je DESNI klik napravljen { line(X[cnt],Y[cnt],X[1],Y[1]); //zatvori poligon! outtext("KRAJ"); //ispiši KRAJ u grafičkom prozoru } } //...program se i dalje "vrti" u petlji i prekida se tek pritiskom na neku tipku tipkovnice closegraph(); //zatvori graficki prozor return 0; }
  • 22. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 22 ISI-Prvasrednjainformatičkaškolasp.j. Grafičke rutine u BGI biblioteci Inicijalizacija grafike: Standardna inicijalizacija BGI grafike kreće pozivom funkcije detectgraph i pozivom funkcije initgraph. Dakle, možete i dalje koristiti taj, standardan način (uobičajen u vrijeme DOS-a) ili ćete koristiti novu jedinstvenu funkciju initwindow. Funkcija ima dva argumenta koji definiraju dimenzije grafičkog prozora u pikselima (širinu i visinu). Na primjer, možete kreirati prozor koji je 450 piksela širok i 350 piksela visok sljedećom naredbom: initwindow(450, 350); BOJE u Winbgim Winbgim paket podržava dva sustava boja koji se mogu koristiti s bilo kojom funkcijom koja očekuje boje kao argumente: šesnaest uobičajenih BGI boja označenih cjelobrojnim vrijednostima (integer) od 0 do 15, kojima možemo dati simbolička imena: num. oznaka boja engleski naziv hrvatski naziv 0 BLACK CRNA 1 BLUE PLAVA 2 GREEN ZELENA 3 CYAN CIJAN 4 RED CRVENA 5 MAGENTA MAGENTA 6 BROWN SMEĐA 7 LIGHTGRAY SVIJETLOSIVA 8 DARKGRAY TAMNOSIVA 9 LIGHTBLUE SVIJETLOPLAVA 10 LIGHTGREEN SVIJETLOZELENA 11 LIGHTCYAN SVIETLOCIJAN 12 LIGHTRED SVIJETLOCRVENA 13 LIGHTMAGENTA SVIJETLOMAGENTA 14 YELOW ŽUTA 15 WHITE BIJELA RGB boje Boja može biti zadana pomoću tri komponente: crvene, zelene i plave uporabom makro naredbe COLOR(r,g,b). Svaki od r,g,b argumenata mora biti broj u rasponu od 0 do 255. Npr. COLOR(255,100,0) je pretežno crvena boja s dodatkom zelene i bez plave komponente. Ili npr. COLOR(128,128,128) reprezentira svijetlo sivu boju, dok je COLOR (255,255,255) čista bijela boja. Ove boje također mogu biti očitane s ekrana pomoću BGI funkcije getbkcolor. Sljedeće makro naredbe (RED_VALUE, GREEN_VALUE, BLUE_VALUE, IS_BGI_COLOR and IS_RGB_COLOR) objašnjene su u sljedećem primjeru: setcolor(BLUE); // Change drawing color to BLUE. setcolor(COLOR(255,100,0); // Change drawing color to reddish-green. setpalette(4, BLUE); // Change palette entry 4 to BLUE. setpalette(4, COLOR(9,9,9));// Change palette entry 4 to nearly black. int current = getcolor( ); // Set current to current drawing color. if (IS_BGI_COLOR(current)) // Check whether it is a BGI color. cout << "Current BGI drawing color is: " << current << end;
  • 23. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 23 ISI-Prvasrednjainformatičkaškolasp.j. if (IS_RGB_COLOR(current)) // Check whether it is an RGB color. cout << "Current RGB drawing color has these components:n" << "Red: " << RED_VALUE(current) << 'n' << "Green: " << GREEN_VALUE(current) << 'n' << "Blue: " << BLUE_VALUE(current) << 'n' int getdisplaycolor(int color) Aktualna boja postavljena na zaslon naredbom putpixel možda neće odgovarati egzaktnoj RGB boji koju smo željeli postići zbog ograničenja grafičkog moda koji je trenutno aktivan. Povratna vrijednost ove funkcije daje vrijednost koja aktualna boja bi bila vidljiva na ekranu za zadane parametre boje. Upravljanje ulaza preko TIPKOVNICE Imamo na raspolaganju tri funkcije koje su originalni dio Borlandovog conio.h. Ove su funkcije sadržane u winbgim.h i nema potrebe za uključivanjem conio.h: void delay(int milisec) – zaustavlja računanje za specificirani broj milisekundi int getch( ) – "hvata" tipku koju smo odtipkali i ne zaustavlja program onom dosadnom frazom ...press any key to continue. Očitana tipka je u obliku ASCII vrijednosti. Ako ju želite pohraniti kao odgovarajući znak na tipkovnici tada trebate napraviti pretvorbu: c = (char) getch( ); Ako pritisnete neku tipku s numeričke tipkovnice (strelice, Home, itd.) tada funkcija getch prvo vraća vrijednost nula (0) a tek u sljedećem pozivu vraća nešto od sljedećeg: KEY_HOME KEY_UP KEY_PGUP KEY_LEFT KEY_CENTER KEY_RIGHT KEY_END KEY_DOWN KEY_PGDN KEY_INSERT KEY_DELETE int kbhit( ) - vraća 0 (nulu) ako niti jedna tipka nije pritisnuta (preciznije: The kbhit function returns 0 if there are no characters now waiting to be read (with getch). It returns a non-zero if there are some characters waiting to be read.) Napredne grafičke naredbe u BGI biblioteci Podrška za dvostruko baferiranje (Double-Buffering) U postojeći BGI milje Adrian Sandor dodao je svije funkcije, getactivepage() and getvisualpage()za podršku dvostrukog baferiranja koje omogućuje animiranu grafiku. One vraćaju broj stranice aktivne stranice (gdje se crtež trenutno nalazi) i vidljive stranice (one koju trenutno gledamo). Originalna winbgi biblioteka dizajnirana je za podršku do 16 stranica, ali winbgim koristi stranicu 1 i 2. Podrška za ispis na grafički prozor Dodan je izlazni kanal, bgiout. Njegova uporaba opisana je u bgiout.html. Podrška za štampanje, učitavanje i zapisivanje grafike Grafički prozor sada ima print opciju u windows meniju tako da korisnik može štampati grafički ekran u bilo kom trenutku. To su sljedeće funkcije:
  • 24. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 24 ISI-Prvasrednjainformatičkaškolasp.j.  getimage  imagesize  printimage  putimage  readimagefile  writeimagefile Podrška za višestruke prozore Initwindow funkcija može biti pozvana višestruko kako bi se moglo kreirati više od jednog grafičkog prozora. The initwindow documentation describes how these multiple windows are used. Ostala dokumentacija za proučavanje BGI grafike  Winbgim functions documentation.  Konstantin Knizhnik's original documentation.  graphics.h header fajl.  source code.  Sample programs: bgidemo0.cpp (extensive program), bgidemo1.cpp (shows registermousehandler), bgidemo2.cpp (shows COLOR macro), bgidemo3.cpp(shows COLOR again), bgidemo4.cpp (shows getmouseclick) that use the winbgim library.  A sample program testget.cpp that uses getch and also shows how to print numbers in graphics mode.  Double-buffering Example dblbuff.cpp. Kako ukloniti konzolni (tzv. DOS) prozor? Primjetili ste da svaki program koji kompilirate s g++ ili bgi++ uvijek otvara DOS prozor. Ako želite spriječiti otvaranje ovog prozora tada dodajte opciju: -mwindows u kompajlersku liniju (odmah iza g++ ili bgi++).
  • 25. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 25 ISI-Prvasrednjainformatičkaškolasp.j. Borland Graphics Interface (BGI) for Windows Version 6.0, August 9, 2004 Sljedeći popis funkcija pretežno je sastavljen od izvornih funkcija iz Borland Graphics Interface-a za DOS programe (razvijenih u tvrtki Borland prije kojih 25 godina...). BGI grafičke funkcije mogu također biti uptrebljene u Windows programima kreiranim s Borland 5.0 prevoditeljem kao i GNU C++ compiler prevoditeljem i vjerojatno još nekim drugim prevoditeljima. Dodatne Windows funkcije su razvijene i opisane na linku: www.cs.colorado.edu/~main/cs1300/doc/bgi/bgi.html. ove funkcije obilježene su oznakom . Također, sve funkcije koje koriste boju mogu se koristiti u RGB sustavu boja (RGB colors). U nastavku je abecedni popis BGI funkcija s linkovima na stranicu s uputama i primjerom uporabe svake od funkcija. Može se dogoditi da s vremenom linkovi budu ugašeni! (Još uvijek rade!) FUNKCIJE: void arc (int x, int y, int stangle, int endangle, int radius); void bar (int left, int top, int right, int bottom); void bar3d (int left, int top, int right, int bottom, int depth, int topflag); ostringstream bgiout; void circle (int x, int y, int radius); void cleardevice (void); void clearmouseclick(int kind); void clearviewport (void); void closegraph (int window=ALL_WINDOWS); int converttorgb (int color); void delay (int millisec); void detectgraph (int *graphdriver, int *graphmode); void drawpoly (int numpoints, int *polypoints); void ellipse (int x, int y, int stangle, int endangle, int xradius, int yradius); void fillellipse (int x, int y, int xradius, int yradius); void fillpoly (int numpoints, int *polypoints); void floodfill (int x, int y, int border); int getactivepage (void); void getarccoords (struct arccoordstype *arccoords); void getaspectratio (int *xasp, int *yasp); int getbkcolor (void); int getch (void); int getcolor (void); int getcurrentwindow (void); struct palettetype* getdefaultpalette (void); int getdisplaycolor (int color); char* getdrivername (void); void getfillpattern (char *pattern); void getfillsettings (struct fillsettingstype *fillinfo); int getgraphmode (void); void getimage (int left, int top, int right, int bottom, void *bitmap); void getlinesettings (struct linesettingstype *lineinfo); int getmaxcolor (void); int getmaxmode (void); int getmaxheight (void); int getmaxwidth (void); int getmaxx (void); int getmaxy (void); char* getmodename (int mode_number); void getmoderange (int graphdriver, int *lomode, int *himode); void getmouseclick(int kind, int& x, int& y); void getpalette (struct palettetype *palette); int getpalettesize (void); int getpixel (int x, int y); void gettextsettings (struct textsettingstype *texttypeinfo); void getviewsettings (struct viewporttype *viewport); int getvisualpage (void); int getwindowheight (void); int getwindowwidth (void);
  • 26. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 26 ISI-Prvasrednjainformatičkaškolasp.j. int getx (void); int gety (void); void graphdefaults (void); char* grapherrormsg (int errorcode); int graphresult(void); unsigned imagesize (int left, int top, int right, int bottom); void initgraph (int *graphdriver, int *graphmode, char *pathtodriver); int initwindow (int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true); int installuserdriver (char *name, int huge (*detect)(void)); int installuserfont (char *name); bool ismouseclick(int kind); int kbhit (void); void line (int x1, int y1, int x2, int y2); void linerel (int dx, int dy); void lineto (int x, int y); int mousex (void); int mousey (void); void moverel (int dx, int dy); void moveto (int x, int y); void outtext (char *textstring); void outtextxy (int x, int y, char *textstring); void pieslice (int x, int y, int stangle, int endangle, int radius); void printimage (const char* title=NULL, double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75, int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX); void putimage (int left, int top, void *bitmap, int op); void putpixel (int x, int y, int color); void readimagefile (const char* filename=NULL, int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX); void rectangle (int left, int top, int right, int bottom); int registerbgidriver (void (*driver)(void)); int registerbgifont (void (*font)(void)); void registermousehandler (int kind, void h(int, int)); void restorecrtmode (void); RGB functions: COLOR(r,g,b), RED_VALUE(v), GREEN_VALUE(v), BLUE_VALUE(v), IS_BGI_COLOR(v), IS_RGB_COLOR(v) void sector (int x, int y, int stangle, int endangle, int xradius, int yradius); void setactivepage (int page); void setallpalette (struct palettetype *palette); void setaspectratio (int xasp, int yasp); void setbkcolor (int color); void setcolor (int color); void setcurrentwindow (int window); void setmousequeuestatus(int kind, bool status=true); void setfillpattern (char *upattern, int color); void setfillstyle (int pattern, int color); unsigned setgraphbufsize (unsigned bufsize); void setgraphmode (int mode); void setlinestyle (int linestyle, unsigned upattern, int thickness); void setpalette (int colornum, int color); void setrgbpalette (int colornum, int red, int green, int blue); void settextjustify (int horiz, int vert); void settextstyle (int font, int direction, int charsize); void setusercharsize (int multx, int divx, int multy, int divy); void setviewport (int left, int top, int right, int bottom, int clip); void setvisualpage (int page); void setwritemode (int mode); int showerrorbox (const char *message); int swapbuffers (void); int textheight (char *textstring); int textwidth (char *textstring); void writeimagefile (const char* filename=NULL,double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75, int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX);
  • 27. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 27 ISI-Prvasrednjainformatičkaškolasp.j. Koje su to naredbe u winbgim.h? WinBGIm donosi preko devedeset novih funkcija koje možemo koristiti u našim programima. Međutim još moramo naučiti i KAKO – treba se još sprijateljiti sa sintaksom i logikom korištenja gore navedenih mogućnosti. Novu paletu funkcija možemo grupirati po sljedećim područjima: CRTAJUĆE funkcije (eng. Drawing Functions) void arc (int x, int y, int stangle, int endangle, int radius ); void bar (int left, int top, int right, int bottom ); void bar3d (int left, int top, int right, int bottom, int depth, int topflag ); void circle (int x, int y, int radius ); void drawpoly (int n_points, int* points); void ellipse (int x, int y, int stangle, int endangle, int xradius, int yradius ); void fillellipse (int x, int y, int xradius, int yradius ); void fillpoly (int n_points, int* points); void floodfill (int x, int y, int border ); void line (int x1, int y1, int x2, int y2 ); void linerel (int dx, int dy ); void lineto( int x, int y ); void pieslice( int x, int y, int stangle, int endangle, int radius ); void putpixel( int x, int y, int color ); void rectangle( int left, int top, int right, int bottom ); void sector( int x, int y, int stangle, int endangle, int xradius, int yradius ); RAZNE funkcije (eng. Miscellaneous Functions) int getdisplaycolor( int color ); int converttorgb( int color ); void delay( int msec ); void getarccoords( arccoordstype *arccoords ); int getbkcolor( ); int getcolor( ); void getfillpattern( char *pattern ); void getfillsettings( fillsettingstype *fillinfo ); void getlinesettings( linesettingstype *lineinfo ); int getmaxcolor( ); int getmaxheight( ); int getmaxwidth( ); int getmaxx( ); int getmaxy( ); bool getrefreshingbgi( ); int getwindowheight( ); int getwindowwidth( ); int getpixel( int x, int y ); void getviewsettings( viewporttype *viewport ); int getx( ); int gety( ); void moverel( int dx, int dy ); void moveto( int x, int y ); void refreshbgi(int left, int top, int right, int bottom); void refreshallbgi( ); void setbkcolor( int color ); void setcolor( int color ); void setfillpattern( char *upattern, int color );
  • 28. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 28 ISI-Prvasrednjainformatičkaškolasp.j. void setfillstyle( int pattern, int color ); void setlinestyle( int linestyle, unsigned upattern, int thickness ); void setrefreshingbgi(bool value); void setviewport( int left, int top, int right, int bottom, int clip ); void setwritemode( int mode ); "PROZORSKE" funkcije (eng. Window Creation / Graphics Manipulation) void initgraph (int *graphdriver, int *graphmode, char *pathtodriver ); int initwindow (int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true ); void cleardevice(); void clearviewport(); void closegraph (int wid=ALL_WINDOWS ); void detectgraph (int *graphdriver, int *graphmode); void getaspectratio (int *xasp, int *yasp); char *getdrivername (); int getgraphmode(); int getmaxmode(); char *getmodename (int mode_number); void getmoderange (int graphdriver, int *lomode, int *himode ); void graphdefaults( ); char *grapherrormsg( int errorcode ); int graphresult( ); int installuserdriver( char *name, int *fp ); // Not available in WinBGI int installuserfont( char *name ); // Not available in WinBGI int registerbgidriver( void *driver ); // Not available in WinBGI int registerbgifont( void *font ); // Not available in WinBGI void restorecrtmode( ); void setaspectratio( int xasp, int yasp ); unsigned setgraphbufsize( unsigned bufsize ); // Not available in WinBGI void setgraphmode( int mode ); void showerrorbox( const char *msg = NULL ); Interakcija s korisnikom (eng. User Interaction) int getch( ); int kbhit( ); User-Controlled Window Functions (winbgi.cpp) int getcurrentwindow( ); void setcurrentwindow( int window ); Double buffering support (winbgi.cpp) int getactivepage( ); int getvisualpage( ); void setactivepage( int page ); void setvisualpage( int page ); void swapbuffers( );
  • 29. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 29 ISI-Prvasrednjainformatičkaškolasp.j. "SLIKOVNE" funkcije (rasterska grafika) (eng. Image Functions (drawing.cpp)) unsigned imagesize( int left, int top, int right, int bottom ); void getimage( int left, int top, int right, int bottom, void *bitmap ); void putimage( int left, int top, void *bitmap, int op ); void printimage( const char* title=NULL, double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75, int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX, bool active=true, HWND hwnd=NULL ); void readimagefile( const char* filename=NULL, int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX ); void writeimagefile( const char* filename=NULL, int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX, bool active=true, HWND hwnd=NULL ); TEKSTNE iliti "PISAJUĆE" funkcije (eng. Text Functions (text.cpp)) void gettextsettings(struct textsettingstype *texttypeinfo); void outtext(char *textstring); void outtextxy(int x, int y, char *textstring); void settextjustify(int horiz, int vert); void settextstyle(int font, int direction, int charsize); void setusercharsize(int multx, int divx, int multy, int divy); int textheight(char *textstring); int textwidth(char *textstring); extern std::ostringstream bgiout; void outstream(std::ostringstream& out=bgiout); void outstreamxy(int x, int y, std::ostringstream& out=bgiout); "MIŠJE" funkcije (eng. Mouse Functions (mouse.cpp)) void clearmouseclick( int kind ); void clearresizeevent( ); void getmouseclick( int kind, int& x, int& y ); bool ismouseclick( int kind ); bool isresizeevent( ); int mousex( ); int mousey( ); void registermousehandler( int kind, void h( int, int ) ); void setmousequeuestatus( int kind, bool status=true ); Upravljanje paletama boja (eng. Palette Functions) palettetype *getdefaultpalette( ); void getpalette( palettetype *palette ); int getpalettesize( ); void setallpalette( palettetype *palette ); void setpalette( int colornum, int color ); void setrgbpalette( int colornum, int red, int green, int blue );
  • 30. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 30 ISI-Prvasrednjainformatičkaškolasp.j. FUNKCIJE, još jednom... ...još jednom, ali direktno iz WinBGIm-a. Uočite crvene markacije, mjesta s greškama koje su ispravljene u priloženim datotekama (JT): // Drawing Functions void arc( int x, int y, int stangle, int endangle, int radius ); void bar( int left, int top, int right, int bottom ); void bar3d( int left, int top, int right, int bottom, int depth, int topflag ); void circle( int x, int y, int radius ); void cleardevice( ); void clearviewport( ); void drawpoly(int n_points, int* points); void ellipse( int x, int y, int stangle, int endangle, int xradius, int yradius ); void fillellipse( int x, int y, int xradius, int yradius ); void fillpoly(int n_points, int* points); void floodfill( int x, int y, int border ); void line( int x1, int y1, int x2, int y2 ); void linerel( int dx, int dy ); void lineto( int x, int y ); void pieslice( int x, int y, int stangle, int endangle, int radius ); void putpixel( int x, int y, int color ); void rectangle( int left, int top, int right, int bottom ); void sector( int x, int y, int stangle, int endangle, int xradius, int yradius ); // Miscellaneous Functions int getdisplaycolor( int color ); int converttorgb( int color ); void delay( int msec ); void getarccoords( arccoordstype *arccoords ); int getbkcolor( ); int getcolor( ); void getfillpattern( char *pattern ); void getfillsettings( fillsettingstype *fillinfo ); void getlinesettings( linesettingstype *lineinfo ); int getmaxcolor( ); int getmaxheight( ); int getmaxwidth( ); int getmaxx( ); int getmaxy( ); bool getrefreshingbgi( ); int getwindowheight( ); int getwindowwidth( ); int getpixel( int x, int y ); void getviewsettings( viewporttype *viewport ); int getx( ); int gety( ); void moverel( int dx, int dy ); void moveto( int x, int y ); void refreshbgi(int left, int top, int right, int bottom); void refreshallbgi( ); void setbkcolor( int color ); void setcolor( int color ); void setfillpattern( char *upattern, int color ); void setfillstyle( int pattern, int color ); void setlinestyle( int linestyle, unsigned upattern, int thickness ); void setrefreshingbgi(bool value); void setviewport( int left, int top, int right, int bottom, int clip );
  • 31. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 31 ISI-Prvasrednjainformatičkaškolasp.j. void setwritemode( int mode ); // Window Creation / Graphics Manipulation void closegraph( int wid=ALL_WINDOWS ); void detectgraph( int *graphdriver, int *graphmode ); void getaspectratio( int *xasp, int *yasp ); char *getdrivername( ); int getgraphmode( ); int getmaxmode( ); char *getmodename( int mode_number ); void getmoderange( int graphdriver, int *lomode, int *himode ); void graphdefaults( ); char *grapherrormsg( int errorcode ); int graphresult( ); void initgraph( int *graphdriver, int *graphmode, char *pathtodriver ); int initwindow ( int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true ); int installuserdriver( char *name, int *fp ); // Not available in WinBGI int installuserfont( char *name ); // Not available in WinBGI int registerbgidriver( void *driver ); // Not available in WinBGI int registerbgifont( void *font ); // Not available in WinBGI void restorecrtmode( ); void setaspectratio( int xasp, int yasp ); unsigned setgraphbufsize( unsigned bufsize ); // Not available in WinBGI void setgraphmode( int mode ); void showerrorbox( const char *msg = NULL ); // User Interaction int getch( ); int kbhit( ); // User-Controlled Window Functions (winbgi.cpp) int getcurrentwindow( ); void setcurrentwindow( int window ); // Double buffering support (winbgi.cpp) int getactivepage( ); int getvisualpage( ); void setactivepage( int page ); void setvisualpage( int page ); void swapbuffers( ); // Image Functions (drawing.cpp) unsigned imagesize( int left, int top, int right, int bottom ); void getimage( int left, int top, int right, int bottom, void *bitmap ); void putimage( int left, int top, void *bitmap, int op ); void printimage( const char* title=NULL, double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75, int left=0, int right=0, int right=INT_MAX, int bottom=INT_MAX, bool active=true, HWND hwnd=NULL );
  • 32. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 32 ISI-Prvasrednjainformatičkaškolasp.j. void readimagefile( const char* filename=NULL, int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX ); void writeimagefile( const char* filename=NULL, int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX, bool active=true, HWND hwnd=NULL ); // Text Functions (text.cpp) void gettextsettings(struct textsettingstype *texttypeinfo); void outtext(char *textstring); void outtextxy(int x, int y, char *textstring); void settextjustify(int horiz, int vert); void settextstyle(int font, int direction, int charsize); void setusercharsize(int multx, int divx, int multy, int divy); int textheight(char *textstring); int textwidth(char *textstring); extern std::ostringstream bgiout; void outstream(std::ostringstream& out=bgiout); void outstreamxy(int x, int y, std::ostringstream& out=bgiout); // Mouse Functions (mouse.cpp) void clearmouseclick( int kind ); void clearresizeevent( ); void getmouseclick( int kind, int& x, int& y ); bool ismouseclick( int kind ); bool isresizeevent( ); int mousex( ); int mousey( ); void registermousehandler( int kind, void h( int, int ) ); void setmousequeuestatus( int kind, bool status=true ); // Palette Functions palettetype *getdefaultpalette( ); void getpalette( palettetype *palette ); int getpalettesize( ); void setallpalette( palettetype *palette ); void setpalette( int colornum, int color ); void setrgbpalette( int colornum, int red, int green, int blue ); // Color Macros #define IS_BGI_COLOR(v) ( ((v) >= 0) && ((v) < 16) ) #define IS_RGB_COLOR(v) ( (v) & 0x03000000 ) #define RED_VALUE(v) int(GetRValue( converttorgb(v) )) #define GREEN_VALUE(v) int(GetGValue( converttorgb(v) )) #define BLUE_VALUE(v) int(GetBValue( converttorgb(v) )) #undef COLOR int COLOR(int r, int g, int b); // No longer a macro
  • 33. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 33 ISI-Prvasrednjainformatičkaškolasp.j. Napredno korištenje BGI grafike initwindow Syntax #include "graphics.h" int initwindow(int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, closeflag=true); Description The initwindow function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function initializes the graphics system by opening a graphics window of the specified size. The first two parameters (width and height) are required, but all other parameters have default values. The title parameter is the title that will be printed at the top of the window (with a default of "Windows BGI".) The left and top parameters determine the screen coordinates of the left and top sides of the window. The dbflag parameter determines whether double-buffering for the window is automatically turned on as described in the swapbuffers function (true means that double-buffering will be turned on). If the closeflag parameter is true, then the user can click on the window's close button to shut down the entire program. Return Value The original version of initgraph was a void function (with no flag argument), and only one graphics window could be created in any program. The new version allows multiple graphics windows to be created. The return value from the new initwindow function is a unique int identifier that can be used as an argument to setcurrentwindow in order to set which of several windows is currently being used. Immediately after calling initwindow, the current window is always the window that was just created. See also closegraph; getcurrentwindow; getmaxheight; getmaxwidth; initgraph; setcurrentwindow; swapbuffers Example /* initwindow example */ #include "graphics.h" int main(void) { /* initialize graphics window at 400 x 300 */ initwindow(400, 300); /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; } /* initwindow example with two windows */ #include "graphics.h" int main(void) { int wid1, wid2; /* initialize graphics windows */ wid1 = initwindow(400, 300); wid2 = initwindow(300, 400, 200, 100); /* draw lines */ setcurrentwindow(wid1); line(0, 0, getmaxx(), getmaxy()); setcurrentwindow(wid2); line(0, 0, getmaxx(), getmaxy());
  • 34. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 34 ISI-Prvasrednjainformatičkaškolasp.j. /* clean up */ getch(); closegraph(); return 0; } setcurrentwindow Syntax #include "graphics.h" void setcurrentwindow(int window); Description The setcurrentwindow function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function changes the current window for all graphics operations to the specified window. This window number must be a number returned by the initiwindow functiion. The current window is the window where all other graphics operations will take place. Note: Initwindow and initgraph both set the current window to the newly created window, so there is no need to call setcurrentwindow immediately after opening a new window. parameters have default values. See also getcurrentwindow; initgraph; initwindow Example /* setcurrentwindow example */ #include int main(void) { int big; int w, w_right, w_below ; int width, height; // Total width and height of w_left; big = initwindow(getmaxwidth( ), getmaxheight( ), "Big"); w = initwindow(300, 200, "Top/Left Corner"); width = getwindowwidth( ); height = getwindowheight( ); w_right = initwindow(300, 200, "Right", width, 0); w_below = initwindow(300, 200, "Below", 0, height); setcurrentwindow(big); line(0, 0, getmaxwidth( )-1, getmaxheight( )-1); /* clean up */ getch(); closegraph(); return 0; } getcurrentwindow Syntax
  • 35. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 35 ISI-Prvasrednjainformatičkaškolasp.j. #include "graphics.h" int getcurrentwindow( ); Description The getcurrentwindow function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function gets the current window number, which is the window where all graphics operations occur. See also setcurrentwindow; initgraph; initwindow Example /* setcurrentwindow example */ #include void change ( int window ) { int oldwindow = getcurrentwindow( ); setcurrentwindow(window); // Do whatever graphics operations you like in the new current // window... // Restore the original window: setcurrentwindow(oldwindow); } closegraph Syntax #include <graphics.h> void closegraph(int wid=ALL_WINDOWS); Description closegraph deallocates all memory allocated by the graphics system, then restores the screen to the mode it was in before you called initgraph. (The graphics system deallocates memory, such as the drivers, fonts, and an internal buffer, through a call to _graphfreemem.) Return Value None. Windows Notes The windows version of closegraph has an optional parameter called wid which is the window id (returned by initwindow) of the window that is to be closed. This parameter may also be one of two special constant values: CURRENT_WINDOW (causing closegraph to close only the current window), or ALL_WINDOWS (which is the default, causing closegraph to close all open graphics windows). If the current window is closed, then there is no longer a current window and no further drawing operations may be done until a new window is created or a current window is set by calling setcurrentwindow. See also initgraph; initwindow; setgraphbufsize; setcurrentwindow Example /* closegraph example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode, x, y;
  • 36. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 36 ISI-Prvasrednjainformatičkaškolasp.j. /* initialize graphics mode */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "Press a key to close the graphics system:"); getch(); /* wait for a key */ /* closes down the graphics system */ closegraph(); printf("We're now back in text mode.n"); printf("Press any key to halt:"); getch(); return 0; } swapbuffers Syntax #include "graphics.h" void swapbuffers( ); Description The swapbuffers function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function swaps the roles of the current active and the current visual graphics buffers. It is equivalent to these statements: int oldv = getvisualpage( ); int olda = getactivepage( ); setvisualpage(olda); setactivepage(oldv); See also getactivepage; getvisualpage; initwindow; setactivepage; setvisualpage getactivepage Syntax #include "graphics.h" int getactivepage(void); Description The getactivepage function is available in the winbgim implementation of BGI graphics. getactivepage gets the page number of the currently active page (where drawing takes place). The active graphics page might not be the one you see onscreen, depending on how many graphics pages are available on your system. The original winbgi was designed to support up to 16 pages, but I have only used pages 1 and 2 myself. NOTE: Using page number 0 might mess up the colors. I use pages 1-2 for double buffering. Return Value
  • 37. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 37 ISI-Prvasrednjainformatičkaškolasp.j. The page number of the currently active page. See also getvisualpage; setactivepage; swapbuffers getvisualpage Syntax #include "graphics.h" int getvisualpage(void); Description The getvisualpage function is available in the winbgim implementation of BGI graphics. getvisualpage gets the page number of the currently visable page (which is visible on the screen). The visual graphics page might not be the one where drawing currnetly takes place. The original winbgi was designed to support up to 16 pages, but I have only used pages 1 and 2 myself. NOTE: Using page number 0 might mess up the colors. I use pages 1-2 for double buffering. Return Value The page number of the currently visible page. See also getactivepage; setvisualpage; swapbuffers setactivepage Syntax #include <graphics.h> void setactivepage(int page); Description setactivepage makes page the active graphics page. All subsequent graphics output will be directed to that graphics page. The active graphics page might not be the one you see onscreen, depending on how many graphics pages are available on your system. Only the EGA, VGA, and Hercules graphics cards support multiple pages. Return Value None. See also setvisualpage; swapbuffers Example /* setactivepage example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* select driver and mode that supports multiple pages */ int gdriver = EGA, gmode = EGAHI, errorcode; int x, y, ht; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ {
  • 38. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 38 ISI-Prvasrednjainformatičkaškolasp.j. printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; ht = textheight("W"); /* select the off screen page for drawing */ setactivepage(1); /* draw a line on page #1 */ line(0, 0, getmaxx(), getmaxy()); /* output a message on page #1 */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "This is page #1:"); outtextxy(x, y+ht, "Press any key to halt:"); /* select drawing to page #0 */ setactivepage(0); /* output a message on page #0 */ outtextxy(x, y, "This is page #0."); outtextxy(x, y+ht, "Press any key to view page #1:"); getch(); /* select page #1 as the visible page */ setvisualpage(1); /* clean up */ getch(); closegraph(); return 0; } setvisualpage Syntax #include <graphics.h> void setvisualpage(int page); Description setvisualpage makes page the visual graphics page. Return Value None. See also graphresult; setactivepage; swapbuffers Example /* setvisualpage example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* select driver and mode that supports multiple pages */ int gdriver = EGA, gmode = EGAHI, errorcode; int x, y, ht;
  • 39. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 39 ISI-Prvasrednjainformatičkaškolasp.j. /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; ht = textheight("W"); /* select the off screen page for drawing */ setactivepage(1); /* draw a line on page #1 */ line(0, 0, getmaxx(), getmaxy()); /* output a message on page #1 */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "This is page #1:"); outtextxy(x, y+ht, "Press any key to halt:"); /* select drawing to page #0 */ setactivepage(0); /* output a message on page #0 */ outtextxy(x, y, "This is page #0."); outtextxy(x, y+ht, "Press any key to view page #1:"); getch(); /* select page #1 as the visible page */ setvisualpage(1); /* clean up */ getch(); closegraph(); return 0; } setviewport Syntax #include <graphics.h> void setviewport(int left, int top, int right, int bottom, int clip); Description setviewport establishes a new viewport for graphics output. The viewport corners are given in absolute screen coordinates by (left,top) and (right,bottom). The current position (CP) is moved to (0,0) in the new window. The parameter clip determines whether drawings are clipped (truncated) at the current viewport boundaries. If clip is nonzero, all drawings will be clipped to the current viewport. Return Value If invalid input is passed to setviewport, graphresult returns -11, and the current view settings remain unchanged. See also clearviewport; getviewsettings; graphresult Example /* setviewport example */ #include <graphics.h> #include <stdlib.h>
  • 40. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 40 ISI-Prvasrednjainformatičkaškolasp.j. #include <stdio.h> #include <conio.h> #define CLIP_ON 1 /* activates clipping in viewport */ int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } setcolor(getmaxcolor()); /* message in default full-screen viewport */ outtextxy(0, 0, "* <-- (0, 0) in default viewport"); /* create a smaller viewport */ setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON); /* display some text */ outtextxy(0, 0, "* <-- (0, 0) in smaller viewport"); /* clean up */ getch(); closegraph(); return 0; } clearviewport Syntax #include <graphics.h> void clearviewport(void); Description clearviewport erases the viewport and moves the CP (current position) to home (0,0), relative to the viewport. Return Value None. See also cleardevice; getviewsettings; setviewport Example /* clearviewport example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #define CLIP_ON 1 /* activates clipping in viewport */ int main(void)
  • 41. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 41 ISI-Prvasrednjainformatičkaškolasp.j. { /* request autodetection */ int gdriver = DETECT, gmode, errorcode, ht; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } setcolor(getmaxcolor()); ht = textheight("W"); /* message in default full-screen viewport */ outtextxy(0, 0, "* <-- (0, 0) in default viewport"); /* create a smaller viewport */ setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON); /* display some messages */ outtextxy(0, 0, "* <-- (0, 0) in smaller viewport"); outtextxy(0, 2*ht, "Press any key to clear viewport:"); getch(); /* wait for a key */ clearviewport(); /* clear the viewport */ /* output another message */ outtextxy(0, 0, "Press any key to quit:"); /* clean up */ getch(); closegraph(); return 0; } getx Syntax #include <graphics.h> int getx(void); Description getx finds the current graphics position's x-coordinate. The value is viewport-relative. Return Value getx returns the x-coordinate of the current position. See also getmaxx; getviewsettings; gety; moveto Example /* getx example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; char msg[80];
  • 42. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 42 ISI-Prvasrednjainformatičkaškolasp.j. /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move to the screen center point */ moveto(getmaxx() / 2, getmaxy() / 2); /* create a message string */ sprintf(msg, "<-(%d, %d) is the here.", getx(), gety()); /* display the message */ outtext(msg); /* clean up */ getch(); closegraph(); return 0; } gety Syntax #include <graphics.h> int gety(void); Description gety returns the current graphics position's y-coordinate. The value is viewport-relative. Return Value gety returns the y-coordinate of the current position. See also getmaxy; getviewsettings; getx; moveto Example /* gety example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ }
  • 43. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 43 ISI-Prvasrednjainformatičkaškolasp.j. /* move to the screen center point */ moveto(getmaxx() / 2, getmaxy() / 2); /* create a message string */ sprintf(msg, "<-(%d, %d) is the here.", getx(), gety()); /* display the message */ outtext(msg); /* clean up */ getch(); closegraph(); return 0; } moveto Syntax #include <graphics.h> void moveto(int x, int y); Description moveto moves the current position (CP) to viewport position (x,y). Return Value None. See also moverel Example /* moveto example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move the CP to location (20,30) */ moveto(20,30); /* plot a pixel at the CP */ putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at (20,30) */ sprintf(msg, " (%d, %d)", getx(), gety()); outtextxy(20,30, msg); /* move to (100,100) */ moveto(100,100); /* plot a pixel at the CP */
  • 44. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 44 ISI-Prvasrednjainformatičkaškolasp.j. putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at CP */ sprintf(msg, " (%d, %d)", getx(), gety()); outtext(msg); /* clean up */ getch(); closegraph(); return 0; } moverel Syntax #include <graphics.h> void moverel(int dx, int dy); Description moverel moves the current position (CP) dx pixels in the x direction and dy pixels in the y direction. Return Value None. See also moveto Example /* moverel example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move the CP to location (20,30) */ moveto(20,30); /* plot a pixel at the CP */ putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at (20,30) */ sprintf(msg, " (%d, %d)", getx(), gety()); outtextxy(20,30, msg); /* move to a point a relative distance away from the current CP */ moverel(100, 100); /* plot a pixel at the CP */ putpixel(getx(), gety(), getmaxcolor());
  • 45. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 45 ISI-Prvasrednjainformatičkaškolasp.j. /* create and output a message at CP */ sprintf(msg, " (%d, %d)", getx(), gety()); outtext(msg); /* clean up */ getch(); closegraph(); return 0; } getmaxx Syntax #include <graphics.h> int getmaxx(void); Description getmaxx returns the maximum (screen-relative) x value for the current graphics driver and mode. For example, on a CGA in 320*200 mode, getmaxx returns 319. getmaxx is invaluable for centering, determining the boundaries of a region onscreen, and so on. Return Value getmaxx returns the maximum x screen coordinate. See also getmaxy; getwindowwidth; getx Example /* getmaxx example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; char xrange[80], yrange[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* convert max resolution values to strings */ sprintf(xrange, "X values range from 0..%d", getmaxx()); sprintf(yrange, "Y values range from 0..%d", getmaxy()); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, xrange); outtextxy(midx, midy + textheight("W"), yrange);
  • 46. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 46 ISI-Prvasrednjainformatičkaškolasp.j. /* clean up */ getch(); closegraph(); return 0; } getwindowwidth Syntax #include <graphics.h> int getwindowwidth(void); Description The getwindowwidth function is available in the winbgim implementation of BGI graphics. The function returns the total width of the window including nondrawable border areas. Return Value getwindowwidth returns the total width of the window See also getmaxx; getwindowheight; getx Example /* getwindowwidth example */ #include <graphics.h> int main(void) { int w_left, w_right; int width; // Total width of w_left; // Make two windows, side by side */ w_left = initwindow(300, 200); width = getwindowwidth( ); w_right = initwindow(300, 200, width, 0); /* clean up */ getch(); closegraph(); return 0; } getwindowheight Syntax #include <graphics.h> int getwindowheight(void); Description The getwindowheight function is available in the winbgim implementation of BGI graphics. The function returns the total height of the window including nondrawable border areas. Return Value getwindowheight returns the total height of the window See also getmaxy; getwindowwidth; gety Example
  • 47. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 47 ISI-Prvasrednjainformatičkaškolasp.j. /* getwindowheight example */ #include <graphics.h> int main(void) { int w_above, w_below; int height; // Total height of w_above; // Make two windows, one on top of the other */ w_above = initwindow(300, 200); height = getwindowheight( ); w_below = initwindow(300, 200, 0, height); /* clean up */ getch(); closegraph(); return 0; } setcolor Syntax #include <graphics.h> void setcolor(int color); Description setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor. The current drawing color is the value to which pixels are set when lines, and so on are drawn. The drawing colors shown below are available for the CGA and EGA, respectively. Palette Number Three Colors 0 LIGHTGREEN LIGHTRED YELLOW 1 LIGHTCYAN LIGHTMAGENTA WHITE 2 GREEN RED BROWN 3 CYAN MAGENTA LIGHTGRAY Name Value BLACK 0 BLUE 1 GREEN 2 CYAN 3 RED 4 MAGENTA 5 BROWN 6 LIGHTGRAY 7 DARKGRAY 8 LIGHTBLUE 9 LIGHTGREEN 10 LIGHTCYAN 11 LIGHTRED 12 LIGHTMAGENTA 13 YELLOW 14 WHITE 15 You select a drawing color by passing either the color number itself or the equivalent symbolic name to setcolor. For example, in CGAC0 mode, the palette contains four colors: the background color, light green, light red, and yellow. In this mode, either setcolor(3) or setcolor(CGA_YELLOW) selects a drawing color of yellow. Return Value
  • 48. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 48 ISI-Prvasrednjainformatičkaškolasp.j. None. Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or anRGB color. Example /* setcolor example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* select driver and mode that supports multiple drawing colors */ int gdriver = EGA, gmode = EGAHI, errorcode; int color, maxcolor, x, y; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(); /* for centering text messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); x = getmaxx() / 2; y = getmaxy() / 2; /* loop through the available colors */ for (color=1; color<=maxcolor; color++) { cleardevice(); /* clear the screen */ setcolor(color); /* select new background color */ /* output a messsage */ sprintf(msg, "Color: %d", color); outtextxy(x, y, msg); getch(); } /* clean up */ closegraph(); return 0; } See also getpalette ; getpalettesize ; graphresult ; setbkcolor ; setcolor setpalette
  • 49. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 49 ISI-Prvasrednjainformatičkaškolasp.j. setbkcolor Syntax #include <graphics.h> void setbkcolor(int color); Description setbkcolor sets the background to the color specified by color. The argument color can be a name or a number as listed below. (These symbolic names are defined in graphics.h.) Name Value BLACK 0 BLUE 1 GREEN 2 CYAN 3 RED 4 MAGENTA 5 BROWN 6 LIGHTGRAY 7 DARKGRAY 8 LIGHTBLUE 9 LIGHTGREEN 10 LIGHTCYAN 11 LIGHTRED 12 LIGHTMAGENTA 13 YELLOW 14 WHITE 15 For example, if you want to set the background color to blue, you can call setbkcolor(BLUE) /* or */ setbkcolor(1) On CGA and EGA systems, setbkcolor changes the background color by changing the first entry in the palette. If you use an EGA or a VGA, and you change the palette colors with setpalette or setallpalette, the defined symbolic constants might not give you the correct color. This is because the parameter to setbkcolor indicates the entry number in the current palette rather than a specific color (unless the parameter passed is 0, which always sets the background color to black). Return Value None. Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or anRGB color. Also, only future drawing will use the new background color (anything currently drawn in the old background color will stay in the old color). Calling setbkcolor(0) will change the background color to the current color at index [0] of the palette (rather than always changing the background to black). See also getbkcolor; setallpalette; setcolor;setpalette Example
  • 50. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 50 ISI-Prvasrednjainformatičkaškolasp.j. /* setbkcolor example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* _select driver and mode that supports multiple background colors*/ int gdriver = EGA, gmode = EGAHI, errorcode; int bkcol, maxcolor, x, y; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %sn", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(); /* for centering text messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); x = getmaxx() / 2; y = getmaxy() / 2; /* loop through the available colors */ for (bkcol=0; bkcol<=maxcolor; bkcol++) { /* clear the screen */ cleardevice(); /* select a new background color */ setbkcolor(bkcol); /* output a messsage */ if (bkcol == WHITE) setcolor(EGA_BLUE); sprintf(msg, "Background color: %d", bkcol); outtextxy(x, y, msg); getch(); } /* clean up */ closegraph(); return 0; } getch Syntax #include "graphics.h" int getch(void); Description The getch function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function reads one character from the keyboard and returns its ASCII value (without waiting for a return key). In order to work, the user must click in the graphics window (i.e., the Windows focus must be in the graphics window). For special keys, the getch function first returns ASCII 0. The next call will then return one of these special keys:
  • 51. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 51 ISI-Prvasrednjainformatičkaškolasp.j. #define KEY_HOME 71 #define KEY_UP 72 #define KEY_PGUP 73 #define KEY_LEFT 75 #define KEY_CENTER 76 #define KEY_RIGHT 77 #define KEY_END 79 #define KEY_DOWN 80 #define KEY_PGDN 81 #define KEY_INSERT 82 #define KEY_DELETE 83 #define KEY_F1 59 #define KEY_F2 60 #define KEY_F3 61 #define KEY_F4 62 #define KEY_F5 63 #define KEY_F6 64 #define KEY_F7 65 #define KEY_F8 66 #define KEY_F9 67 Return Value The ASCII value of a key that has been pressed. See also kbhit Example #include "graphics.h" #include <stdio.h> // Provides sprintf #include <iostream.h> // Provides cout void outintxy(int x, int y, int value); int main( ) { int i; char c; // Initialize the graphics window. init_window(400, 300); // Convert some numbers to strings and draw them in graphics window: outtextxy(10, 10, "Here are some numbers:"); for (i = 10; i <= 100; i += 10) outintxy(20, i+10, i); // Get some characters from the keyboard until an X is typed: outtextxy(20, 130, "Click in this graphics window,"); outtextxy(20, 140, "and then press arrow keys."); outtextxy(20, 150, "Watch the console window while pressing."); outtextxy(20, 160, "Press X to exit."); do { c = (char) getch( ); if (c != 0) cout << "That is ASCII value: " << (int) c << endl; else { // Process one of the special keys: c = (char) getch( ); switch (c) { case KEY_HOME: cout << "Home key." << endl; break; case KEY_UP: cout << "Up key." << endl; break; case KEY_PGUP: cout << "PgUp key." << endl; break; case KEY_LEFT: cout << "Left key." << endl; break; case KEY_CENTER: cout << "Center key." << endl; break; case KEY_RIGHT: cout << "Right key." << endl; break; case KEY_END: cout << "End key." << endl; break; case KEY_DOWN: cout << "Down key." << endl; break; case KEY_PGDN: cout << "PgDn key." << endl; break; case KEY_INSERT: cout << "Insert key." << endl; break; case KEY_DELETE: cout << "Delete key." << endl; break; case KEY_F1: cout << "F1 key." << endl; break; case KEY_F2: cout << "F2 key." << endl; break;
  • 52. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 52 ISI-Prvasrednjainformatičkaškolasp.j. case KEY_F3: cout << "F3 key." << endl; break; case KEY_F4: cout << "F4 key." << endl; break; case KEY_F5: cout << "F5 key." << endl; break; case KEY_F6: cout << "F6 key." << endl; break; case KEY_F7: cout << "F7 key." << endl; break; case KEY_F8: cout << "F8 key." << endl; break; case KEY_F9: cout << "F9 key." << endl; break; default: cout << "Unknown extended key." << endl; } } } while ((c != 'x') && (c != 'X')); closegraph( ); } void outintxy(int x, int y, int value) { char digit_string[20]; sprintf(digit_string, "%d", value); outtextxy(x, y, digit_string); } kbhit Syntax #include "graphics.h" int kbhit(void); Description The kbhit function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function returns true (non-zero) if there is a character in the input buffer ready to read. Otherwise it returns false. In order to work, the user must click in the graphics window (i.e., the Windows focus must be in the graphics window). Return Value True (non-zero) if there is a character in the input buffer, otherwise false. See also getch Example #include "graphics.h" #include <stdio.h> // Provides sprintf void outintxy(int x, int y, int value); int main( ) { int i; // Initialize the graphics window. init_window(400, 300); // Convert some numbers to strings and draw them in graphics window: outtextxy(20, 130, "Click in this graphics window,"); outtextxy(20, 140, "and then press a key to stop."); outtextxy(10, 10, "Here are some numbers:"); for (i = 0; !kbhit( ); i++) { outintxy(20 + (i/10)*40 , (i % 10)*+10, i); delay(4000); } closegraph( ); } void outintxy(int x, int y, int value) { char digit_string[20];
  • 53. PROGRAMIRAJMO GRAFIKU uz BGI, Jadranko Tudović s t r a n a | 53 ISI-Prvasrednjainformatičkaškolasp.j. sprintf(digit_string, "%d", value); outtextxy(x, y, digit_string); }