Home

Introduction to Graphics

 

Introduction to Device Contexts

 

Overview

A device context is an ensemble of the tools needed to draw lines, shapes, and other graphics. It includes the platform you draw on, the dimensioning of the platform, the orientation and other variations of your drawing, the tools you need to draw on the platform, the colors, and various other accessories that can complete your imagination. To provide support for drawing on the Windows operating system, Microsoft created the Graphical Device Interface, abbreviated as GDI. It is a set of classes, functions, variables, and constants that group all or most of everything you need to draw on an application. The GDI is provided as a library called Gdi.dll and is already installed on your computer.

   

Practical LearningPractical Learning: Introducing Graphics

  1. Start Embarcadero RAD Studio
  2. To create a new project, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  3. In the Object Inspector, click Caption and type Nature and Resources
  4. Click Name and type frmMain
  5. To save the project, on the Standard toolbar, click the Save All button
  6. Click the Create New Folder
  7. Type NatureResources1 as the name of the folder and press Enter twice to display its content
  8. Change the file name to Nature and press Enter
  9. Change the project name as NatureResources and press Enter
  10. Right-click the following picture and click Copy
     
    Papaya
  11. Use a file utility such as Windows Explorer and locate the folder that contains this project
  12. Right-click it and click Paste

The Canvas

In a Win32 application, in order to draw, you must create a device context. This can be taken care of by declaring a variable of type HDC. To keep track of the various drawings, the device context uses a coordinate system that has its origin (0, 0) on the top-left corner of the desktop:

Anything that is positioned on the screen is based on this origin. This coordinate system can get the location of an object using a horizontal and a vertical measurement. The horizontal measures are based on an x axis that moves from the origin to the right direction. The vertical measures use a y axis that moves from the origin to the bottom direction:

This means that, if you start drawing something such as a line, it would start on the origin and continue where you want it to stop. To significantly simplify drawing and make it compatible with the VCL, the library has a class called TCanvas. TCanvas is derived from the TCustomCanvas class that is based on TPersistent, which is derived from TObject:

TCanvas Inheritance

To further make it easy to draw, every control that needs drawing already has a TCanvas variable available. This means that you usually will not have to declare a TCanvas variable before drawing.

In a VCL application, a canvas is the object on which you draw but the TCanvas class actually includes everything that can be used to draw. This includes the platform (like a piece of paper on which you draw) and the tools (like the pens and colors, etc).

A Handle to the Canvas

To support graphics and drawing, the Win32 library provides a handle named HDC (handle to the device context). To give you access to this handle, the TCanvas class is equipped with a property named Handle, which is of type HDC:

__property HDC__ * Handle = {read=GetHandle,write=SetHandle};

The Handle property allows you to perform additional operations that may not be available in  the TCanvas class.

Introduction to Bitmaps

 

Overview

A bitmap is a graphic object used to display a picture on a window or to store it in the computer memory as a file. It is the primary type of graphics used for various occasions. For example, a bitmap can be used as a background for a window. That is the case for the Pinball game that ships with some versions of Microsoft Windows:

A bitmap can also be used for aesthetic purposes to decorate a dialog box. Probably the most regular use of bitmaps is as small graphics on toolbars:

There are three main ways you create or add a bitmap to your application. You can create an array of byte values that describe the bitmap. You can design a bitmap using a low-level bitmap application like Image Editor, or you can use a professional picture.

Visually Creating a Bitmap

There are three types of bitmaps we will be creating for our lessons. The simplest consists of designing a regular picture made of colors from an (external) application such Windows Paint. Another technique consists of declaring an array of bits that describes the bitmap; then translate this array into a handle to bitmap before actually using it. The last technique, which requires some design or importing, consists of using a more advance picture in an application.

Creating a bitmap and making it available to an application is just one aspect. The goal is to use such a bitmap or to decide what to use it for. Normally, the way you create a bitmap has some influence on where and how that bitmap is used.

Paint (or Windows Paint) is an application that gets installed with Microsoft Windows. It provides a cheap solution to creating or maipulating bitmaps:

Windows Paint
 

Introduction to the VCL Support For Bitmaps

 

Programmatically Creating a Bitmap

The VCL provides support for bitmaps through the TBitmap class from the Graphics namespace. The TBitmap class is based on TGraphic. The TGraphic class is derived form TInterfacedPersistent that itself is naturally based on the TPersistent class:

TBitmap Inheritance

Some classes already have a Bitmap property that you can use to initialize appropriately. In most cases, you will need to declare a pointer to TBitmap. To do this, you must precede the name of the class with the Graphics namespace. Here is an example:

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
    Graphics::TBitmap *bmpSomething = new Graphics::TBitmap;
}
//---------------------------------------------------------------------------

Like all other dynamic objects, after using the bitmap, you should delete it. If you declare it locally, you can also delete it in the same event or method. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormDblClick(TObject *Sender)
{
	Graphics::TBitmap *bmpSomething = new Graphics::TBitmap;

	try {
		// Treat the bitmap file here
	}
	__finally
	{
		// Time to delete the pointer
		delete bmpSomething;
	}
}
//---------------------------------------------------------------------------

If you declare the variable globally, make sure you delete it when the application is destroyed. After declaring the variable, you must initialize it appropriately before actually using it.

Dismssing a Bitmap

A picture is one of those of those objects that consume computer resources. This means that, if you create a picture, use it as you see fit. Once you don't need it anymore, you should release its resources to make them available to other applications. To free the resources of a bitmap, you have various options.

If you are using a picture locally, to declare its pointer, you can use the auto_ptr class of the std namespace of the STL. Here is an example:

//---------------------------------------------------------------------------

#include <vcl.h>
#include <memory>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
    std::auto_ptr<Graphics::TBitmap> bmpSomething(new Graphics::TBitmap);
}
//---------------------------------------------------------------------------

In this case, you let the operating system take care of memory. In other words, once the pointer is not used anymore, such as when the application closes, the operating system will delete the object and reclaim the memory area the variable was using.

To support its own ability to free resources used by its descendants, the TObject class is equipped with a method named Free. Its syntax is:

int __fastcall Free(void);

Call this method to reclaim the resources that a pointer was using once you know the pointer doesn't need those resources anymore.

Bitmap Drawing

Once the file is ready, you can use it in your application. For example, you can display it on a form. Because the form is equipped with a canvas, to display a picture, you can call the TCanvas::Draw() method. Its syntax is:

void __fastcall Draw(int X, int Y, TGraphic* Graphic);

The X and Y values specify the corner from where to start drawing. Normally, it will be the top-left coordinates of the picture. The Graphic parameter is the graphic object to draw on the canvas. This would be done as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormDblClick(TObject *Sender)
{
	Graphics::TBitmap *bmpSomething = new Graphics::TBitmap;

	try {
		Canvas->Draw(10, 10, bmpSomething);
	}
	__finally
	{
		delete bmpSomething;
	}
}
//---------------------------------------------------------------------------
 

Bitmap Loading From a File

In order to use a bitmap in your application, you must import it from its file to the application. The easiest way to do this consists of calling the TGraphic::LoadFromFile() method. Its syntax is:

virtual void __fastcall LoadFromFile(System::UnicodeString Filename);

This method is particularly easy to use as long as you know the location of the bitmap file. If the picture is in the same directory as the current project, you can simply type its name and its extension as a string and pass it as argument. An example would be:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormDblClick(TObject *Sender)
{
	Graphics::TBitmap * picture = new Graphics::TBitmap;

	try {
		picture->LoadFromFile("student.bmp");
		Canvas->Draw(10, 10, picture);
	}
	__finally
	{
		delete picture;
	}
}
//---------------------------------------------------------------------------

If the file is not in the same directory as the project, you may have to specify its complete path. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormDblClick(TObject *Sender)
{
	Graphics::TBitmap * picture = new Graphics::TBitmap;

	try {
		picture->LoadFromFile("C:\\Exercise\\student.bmp");
		Canvas->Draw(10, 10, picture);
	}
	__finally
	{
		delete picture;
	}
}
//---------------------------------------------------------------------------

If the file, its path, and its extension are correct, the file can be used:

Bitmap

If the file does not exist when you try accessing it, in other words, if the file or the path you specified is not valid (the file and the path are not checked at compilation time, they are checked when the application is asked to retrieve the bitmap), you would receive an error. The exception thrown is of type EFOpenError (which stands for Exception-File-Open-Error), meaning that the information given about opening the file is incorrect somewhere. You can display our own message as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormDblClick(TObject *Sender)
{
    Graphics::TBitmap * picture = new Graphics::TBitmap;

    try {
	try {
		picture->LoadFromFile("C:\\Exercise\\something.bmp");
		Canvas->Draw(10, 10, picture);
	}
	catch(EFOpenError *Error)
	{
	    Application->MessageBox(L"The file path, its name, or its extension"
		   	 	    L"may be invalid or they don't exist.",
				    L"Exercise", MB_OK);
	}
    }
    __finally
    {
	delete picture;
    }
}
//---------------------------------------------------------------------------

Message Box

Bitmap Loading From a Resource File

Another technique you can use to open a bitmap consists of retrieving it from a resource file. Before doing this, you must have a resource file with .res extension. You can create a Windows resource file that has the .rc extension and create a header file that lists its resources. The header file is used to specify a constant number for each resource. For this example, the header file can be named resource.h.

After creating the header file, you can create a resource file, which is a text file with an extension of .rc and, in the file, each resource can be specified using the name of the constant created in the header file.

After creating the resource file, you must import it into your project. This is done by click Project -> Add to Project… from the main menu, selecting the rc file and clicking Open. After adding the resource file, you should compile it to produce a .res file. This makes your file ready.

Once a bitmap in a resource file is ready, to use it in your application, you can call the LoadFromResourceName() method. Its syntax is:

void __fastcall LoadFromResourceName(unsigned Instance, const AnsiString ResName);

The easiest way to do this is to create the resource file in the same directory as the project that is using it. This is because the LoadFromResourceName() method requires the instance of the executable file that contains the resource file. If it is located in the same folder, you can simply pass the instance of the current project as the Instance argument. The second parameter, ResName, is the name of the bitmap to be loaded. Normally, it should be the identifier of the bitmap as defined in the header file.

Bitmap Loading From a Resource Identifier

One more alternative you have into preparing a picture to display in your application consists of using an identifier from a resource file. Since the steps are exactly the same as those used above, we will follow them in a Practical Learning session.

Practical LearningPractical Learning: Loading a Bitmap From Resource

  1. On the main menu of C++Builder, click File -> New -> Other…
  2. In the left list of the New Items dialog box, click C++Builder Files
  3. In the right list, click Header File
  4. Click OK
  5. In the empty file, type
     
    #define PAPAYATREE 1001
  6. Save the file as resource.h and make sure you include the extension. Also, make sure you save it in the folder of the current project
  7. On the Standard toolbar of C++Builder, click the New Items button New Items
  8. In the left list of the New Items dialog box, click Other Files
  9. In the right list, click Text File
  10. Click OK
  11. In the New File dialog box, scroll down and click Resource Script
     
    New File
  12. Click OK
  13. empty file, type:
    #include "resource.h"
    
    PAPAYATREE BITMAP "papaya.bmp"
  14. To save the file, on the Standard toolbar, click the Save button
  15. Type natural.rc as the file name:
     
    Save As
  16. Click Save
  17. While the natural.rc tab is displaying, to compile it, on the main menu, click Project -> Build natural.rc
     
    Build Unit
  18. When the compilation is complete, on the Build Unit dialog box, click OK
  19. On the Object Inspector, click the Events tab and access the OnPaint event of the form
  20. Implement it as follows:
    //---------------------------------------------------------------------------
    
    #include <vcl.h>
    #pragma hdrstop
    
    #include "Nature.h"
    #include "resource.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    #pragma resource "*.dfm"
    TForm1 *Form1;
    //---------------------------------------------------------------------------
    __fastcall TForm1::TForm1(TComponent* Owner)
    	: TForm(Owner)
    {
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::FormPaint(TObject *Sender)
    {
    	Graphics::TBitmap *bmpPapaya = new Graphics::TBitmap;
    
    	try {
    	    try {
    		bmpPapaya->LoadFromResourceID((int)HInstance, PAPAYATREE);
    		Canvas->Draw(0, 0, bmpPapaya);
    	    }
    	    catch(EResNotFound *Problem)
    	    {
    		ShowMessage(L"The resource file was not found "
    			    L"or its name is incorrect.");
    	    }
    	    catch(...)
    	    {
    		ShowMessage("The picture cannot be displayed...");
    	    }
    	}
    	__finally
    	{
    	    delete bmpPapaya;
    	}
    }
    //---------------------------------------------------------------------------
  21. To execute the application, press F9
     
    Bitmap
  22. Close the form and return to your programming environment
  23. To start a new application, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  24. In the Object Inspector, change the following properties:
    Caption: Picture Viewer
    FormStyle: fsMDIForm
    Name: frmPictureViewer
    Position: poScreenCenter
  25. In the Tool Palette, click Dialogs
  26. Click the OpenFileDialog button OpenFileDialog and click the form
  27. In the Object Inspector, change its characteristics as follows:
    (Name): dlgOpen
    Title: Open a Picture
  28. In the Tool Palette, click Standard
  29. Click the TMainMenu button OpenFileDialog and click the form
  30. On the form, right-click MainMenu1 and click Menu Designer...
  31. Right-click somewhere in the Menu Designer and click Insert From Template...
  32. In the Insert Template dialog box, click MDI Frame Menu
     
    Insert Template
  33. Click OK
  34. In the Menu Designer, click the box under Exit
  35. In the Objects Inspector, change the following properties:
    Caption: &Close
    Enabled: (Uncheck to get) False
    Name: mnuFileClose
  36. Click the box under the Close menu item
  37. In the Object Inspector, click Caption, type - and press Enter
  38. Move the Close menu item, and the separator to position them under Save As...
     
    Menu Designer
  39. Double-click the Close menu item
  40. Change the document as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmPictureViewer::mnuFileCloseClick(TObject *Sender)
    {
    	// If there is at least one child document, close it
    	if( MDIChildCount > 0 )
    		ActiveMDIChild->Close();
    
    	// After closing the last document,
    	// check the number of current chil forms.
    	// If there is none, disable the Close menu item
    	if( MDIChildCount == 0 )
    		mnuFileClose->Enabled = False;
    }
    //---------------------------------------------------------------------------
  41. In the Menu Designer, click File and double-click Exit
  42. Close the Menu Designer
  43. Implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmPictureViewer::Exit1Click(TObject *Sender)
    {
    	Close();
    }
    //---------------------------------------------------------------------------
  44. To add a new form, on the main menu, click File -> New -> Form - C++Builder
  45. In the Object Inspector, change the Name to frmView
  46. On top of the Code Editor, click Unit1.cpp to display the first form
  47. On the main menu, click File -> Use Unit...
  48. In the Use Unit dialog box, click Unit2.cpp
  49. Click Header and click OK
 
 
 

Characteristics of a Bitmap

 

Types of Pictures

The TBitmap class is derived from an abstract class named TGraphic. This class provides some of the functionalities that picture files require.

The Microsoft Windows family of operation systems supports various types of pictures. A picture is usually recognized by its type and its extension. Some of the most pupular pictures types are (Microsoft Windows and the VCL support many other file formats):

  • Bitmaps: A regular bitmap is a file with the extension .bmp. These pictures were primarily supported on Microsoft Windows and IBM OS/2 but most (if not all) operating systems can handle them now. To support bitmaps, the VCL provides a class named TBitmap
  • Joint Photographic Experts Group: The JPEG format is one of the most popular types of pictures used on the Internet. It is a picture file with the extension jpg. It can also have the extensions jpeg, jif, or jpe. To support JPEG pictures, the VCL provides the TJPEGImage class. The TJPEGImage class that is defined in the jpeg.hpp header
  • Graphics Interchange Format: Pictures of this type have the extension .gif. To support them, the VCL provides the TGIFImage class, which is defined in the GIFImg header file
  • Portable Network Graphics (PNG): This is one of the most complexes but also the cutest picture file format you will encounter. It provides a picture with no background. To support this file format, the VCL is equipped with a class named TPngImage defined in the  pngimage.hpp header file

All the above picture classes are derived from TGraphic. This class provides them with the most regular operations that picture files would need. Probably the most common operation performed on a file consists of opening one. To support it, all graphic classes inherit a method named LoadFromFile from the TGraphic class. The opposite to opening a file consists of saving one. To provide this functionality, the TGraphic class is equipped with a method named SaveToFile. Its syntax is:

virtual void __fastcall SaveToFile(System::UnicodeString Filename);

Is the Bitmap Empty?

In most circumstances, in order to use a bitmap, you will need to declare a pointer to TBitmap. Because the TBitmap class has only a default constructor, after declaring the pointer, you will need to load a bitmap into it before using it. Once the variable contains a bitmap, you can use it as you see fit. If there is no bitmap stored in t and you attempt to use it, you may receive an error or an unreliable result. If you want to check first whether the variable contains a bitmap, you can check its Empty Boolean value. If the variable contains a bitmap, this property would be true. Otherwise, it would be false.

Practical LearningPractical Learning: Creating an Empty Bitmap

  1. In the top section of the Code Editor, click Unit2.cpp
  2. Under the Code Editor, click Unit2.h
  3. In the public section, declare a few variables as follows:
    //---------------------------------------------------------------------------
    
    #ifndef ViewerH
    #define ViewerH
    //---------------------------------------------------------------------------
    #include <Classes.hpp>
    #include <Controls.hpp>
    #include <StdCtrls.hpp>
    #include <Forms.hpp>
    
    #include <jpeg.hpp>
    #include <GIFImg.hpp>
    #include <pngimage.hpp>
    //---------------------------------------------------------------------------
    enum PictureType { Bitmap, JPEG, GIF, PNG };
    //---------------------------------------------------------------------------
    class TfrmView : public TForm
    {
    __published:	// IDE-managed Components
    private:	// User declarations
    public:		// User declarations
    	Graphics::TBitmap * bmpPicture;
    	TJPEGImage        * jpgPicture;
    	TGIFImage         * gifPicture;
    	TPngImage         * pngPicture;
    
    	PictureType pctType;
    	
    	__fastcall TfrmView(TComponent* Owner);
    };
    //---------------------------------------------------------------------------
    extern PACKAGE TfrmView *frmView;
    //---------------------------------------------------------------------------
    #endif
    
  4. In the Object Inspector, click Events
  5. Double-click OnClose
  6. Implement the event as follows:
    //---------------------------------------------------------------------------
    __fastcall TfrmView::TfrmView(TComponent* Owner)
    	: TForm(Owner)
    {
    	// Initialize the variables
    	bmpPicture = new Graphics::TBitmap;
    	jpgPicture = new TJPEGImage;
    	gifPicture = new TGIFImage;
    	pngPicture = new TPngImage;
    }
    //---------------------------------------------------------------------------
    void __fastcall TfrmView::FormClose(TObject *Sender, TCloseAction &Action)
    {
    	bmpPicture->Free();
    	jpgPicture->Free();
    	gifPicture->Free();
    	pngPicture->Free();
    
    	Action = caFree;
    }
    //---------------------------------------------------------------------------
  7. In the Events section of the Object Inspector, double-click OnPaint
  8. Change the file as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmView::FormPaint(TObject *Sender)
    {
        // Display the picture from the top-left section to the end
        switch(pctType)
        {
    	case PictureType::Bitmap:
    		Canvas->Draw(0, 0, bmpPicture);
    		break;
    	case PictureType::JPEG:
    		Canvas->Draw(0, 0, jpgPicture);
    		break;
    	case PictureType::GIF:
    		Canvas->Draw(0, 0, gifPicture);
    		break;
    	case PictureType::PNG:
    		Canvas->Draw(0, 0, pngPicture);
    		break;
        }
    }
    //---------------------------------------------------------------------------

The Size of a Bitmap

Once a bitmap has been loaded, as a visible object, it has dimensions represented by a width and a height. To support the size of a picture, the TGraphic class is equipped with the Width and the Height properties that the derived classes can use. These are read-write properties, so you can either retrieve these values or change them.

Practical LearningPractical Learning: Getting the Size of a Bitmap

  1. In the top section of the Code Editor, click Unit1.cpp
  2. On the form, double-click MainMenu1
  3. In the Menu Designer, under File, double-click Open
  4. Close the Menu Designer
  5. Implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmPictureViewer::Open1Click(TObject *Sender)
    {
    	if( dlgOpen->Execute() )
    	{
    		TfrmView *frmChild = new TfrmView(Application);
    
    		frmChild->FormStyle = fsMDIChild;
    		mnuFileClose->Enabled = True;
    		String fileExtension = ExtractFileExt(dlgOpen->FileName);
    
    		if( fileExtension == ".bmp" )
    		{
    			frmChild->pctType = PictureType::Bitmap;
    			// Get the picture from the file
    			frmChild->bmpPicture->LoadFromFile(dlgOpen->FileName);
    
    			// Resize the child form to the size of the picture
    			frmChild->ClientWidth  = frmChild->bmpPicture->Width;
    			frmChild->ClientHeight = frmChild->bmpPicture->Height;
    		} // Do the same for the other file types
    		else if( fileExtension == ".jpg" )
    		{
    			frmChild->pctType = PictureType::JPEG;
    			frmChild->jpgPicture->LoadFromFile(dlgOpen->FileName);
    
    			frmChild->ClientWidth  = frmChild->jpgPicture->Width;
    			frmChild->ClientHeight = frmChild->jpgPicture->Height;
    		}
    		else if( fileExtension == ".gif" )
    		{
    			frmChild->pctType = PictureType::GIF;
    			frmChild->gifPicture->LoadFromFile(dlgOpen->FileName);
    
    			frmChild->ClientWidth = frmChild->gifPicture->Width;
    			frmChild->ClientHeight = frmChild->gifPicture->Height;
    		}
    		else if( fileExtension == ".png" )
    		{
    			//std::auto_ptr<TPngImage> pngPicture(new TPngImage());
    			frmChild->pctType = PictureType::PNG;
    			frmChild->pngPicture->LoadFromFile(dlgOpen->FileName);
    
    			frmChild->ClientWidth  = frmChild->pngPicture->Width;
    			frmChild->ClientHeight = frmChild->pngPicture->Height;
    		}
    		else
    		{
    			ShowMessage("Unknown file type");
    			return;
    		}
    
    		// Display the file name in the title bar of the child form
    		frmChild->Caption = ExtractFileName(dlgOpen->FileName);
    	}
    }
    //---------------------------------------------------------------------------
  6. Press F9 to execute
  7. Open a few pictures (some are provides in the resources that accompany these lessons)
     
    Pictures
  8. Close the form(s) and return to your programming environment

The Palette of a Bitmap

A bitmap uses a set of colors known as its palette. To get or set the characteristics of these colors, you can access the Palette property of a TBitmap object.

The Transparency of a Bitmap

When a bitmap displays, it uses all allowable colors and occupies the whole area allocated to its Width and Height values. If you want the bitmap to display only certain parts, set its Transparent property to true.

When designing a picture that would display with transparency, you should use one color to paint the areas that would not display.

Assigning a Bitmap

So far, we have seen first how to declare a TBitmap variable, second how to load it into an application. Once such a bitmap is ready, you can use it in various ways as we saw that you can display it on the form. You can also make a duplicate copy of it and store it in another variable. This can be done using the Assign() method. Its syntax is:

virtual void __fastcall Assign(Classes::TPersistent* Source);

The Source parameter is the variable that holds the bitmap you want to copy and will be assigned to the variable that is making the call.

Getting the Picture of a Form

In some applications, mostly those that use graphics, you may want to get a picture that represents the (contents of the) body of a form. To support this, the TCustomForm class is equipped with a method named GetFormImage and that returns a pointer to TBitmap. The syntax of this function is:

Graphics::TBitmap * __fastcall GetFormImage(void);

After calling this method, you get a picture of the form and you can use it as you see fit.

Win32 Support for Bitmaps

 

Introduction

The primary means of using a bitmap in your application is obviously through the TBitmap class with its properties and methods. If the VCL does not natively provide the bitmap functionality you are using for, you can use one of the Win32 functions.

The Win32 library supports bitmaps through various functions. Most of these functions return a handle to BITMAP, implemented as HBITMAP. To use the return value of one of these, the TBitmap class is equipped with a property named a Handle:

__property HBITMAP__ * Handle = {read=GetHandle,write=SetHandle};

This Handle property is particularly easy to use, just like all Handle properties provided by the TWinControl class to its children. Therefore, anything you would have done on the HBITMAP handle, to use it in your application, simply assign its variable to the TCanvas::Handle and it is made ready.

Bitmap Creation

The most basic bitmap is created from an array of constant values that describe the bitmap. This type is created using the CreateBitmap() function. Its syntax is:

HBITMAP CreateBitmap(int nWidth,
                     int nHeight,
                     UINT cPlanes,
                     UINT cBitsPerPel,
                     CONST VOID *lpvBits);

The nWidth and nHeight parameters specify the dimensions of the bitmap, in pixels. The cPlanes parameter holds the number of color planes used by the device. The cBitsPerPel parameter is an array of color values.

This CreateBitmap() function returns a handle to the BITMAP structure. You can assign that value to the Handle member variable of the TBitmap class. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint(TObject *Sender)
{
	HBITMAP HBmp;
	WORD wBits[] = { 0x00, 0x22, 0x44, 0x88, 0x00, 0x22, 0x44, 0x88,
			 0x22, 0x44, 0x88, 0x00, 0x22, 0x44, 0x88, 0x00,
			 0x44, 0x88, 0x00, 0x22, 0x44, 0x88, 0x00, 0x22,
			 0x88, 0x00, 0x22, 0x44, 0x88, 0x00, 0x22, 0x44 };

	HBmp = CreateBitmap(32, 32, 1, 1, wBits);
}
//---------------------------------------------------------------------------
 
 
   
 

Home Copyright © 2010-2016, FunctionX