quinta-feira, 24 de abril de 2008

Pilha de Quadrados em Borland C++ Builder 6

Esta aplicação plota quadrados a partir de parâmetros fornecidos pela seguinte interface de usuário:

image

Ao clicar no botão "Plotar", um quadrado é instanciado e plotado com o seu canto superior esquerdo dado pelos valores (X,Y) e na largura desejada.

Para manter controle sobre a população de quadrados instanciados, esta aplicação utiliza o conceito de pilha implementado sob a forma de uma classe. Assim, ao clicar no botão "Limpar" a área do paintbox é limpa, permitindo observar a reconstrução dos quadrados na ordem em que são retirados da pilha, através do click no botão "Refazer Tudo". Observe que a aplicação ao retirar um quadrado da pilha, ela salva em outra para não perder o controle sobre todos os quadrados instanciados. Um efeito colateral a ser notado é que a reconstituição é dada na ordem inversa da criação dos quadrados, pois no conceito de pilha, o mais recente será o primeiro a ser retirado da pilha e o mais antigo o último a ser retirado dela (last in, first out - LIFO).

A seguir temos as classes utilizadas:

1) Começando pela classe "Quadrado" (arquivo Unit2.h):

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

#ifndef Unit2H
#define Unit2H

#include <graphics.hpp>             // classe de elementos gráficos do BCB6 

class Quadrado
{
        private:
                int x;
                int y;
                int largura;

        public:
                Quadrado();                                    // construtor default
                Quadrado( int, int );                         // construtor
                Quadrado( int, int, int );                   // construtor
                void Plotar( Graphics::TBitmap * );
                ~Quadrado();                                 // destrutor
};

//---------------------------------------------------------------------------
#endif

 

2) E os métodos previstos para esta classe (arquivo Unit2.cpp):

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

#pragma hdrstop

#include "Unit2.h"          // classe Quadrado

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

#pragma package(smart_init)

Quadrado :: Quadrado( )                               // construtor default
{
        this->x = 100;
        this->y = 200;
        this->largura = 90;
}

Quadrado :: Quadrado( int a, int b )                 // construtor
{
        this->x = a;
        this->y = b;
        this->largura = 50;
}

Quadrado :: Quadrado( int a, int b, int c)           // construtor
{
        this->x = a;
        this->y = b;
        this->largura = c;
}

void Quadrado :: Plotar( Graphics::TBitmap *tmp )
{
        tmp->Canvas->PenPos = TPoint( this->x, this->y );
        tmp->Canvas->LineTo( this->x + this->largura, this->y  );

        //tmp->Canvas->PenPos = TPoint( this->x + this->largura, this->y );
        tmp->Canvas->LineTo( this->x + this->largura, this->y + this->largura );

        //tmp->Canvas->PenPos = TPoint( this->x + this->largura, this->y + this->largura );
        tmp->Canvas->LineTo( this->x, this->y + this->largura  );

        //tmp->Canvas->PenPos = TPoint( this->x, this->y + this->largura );
        tmp->Canvas->LineTo( this->x, this->y  );

}

Quadrado :: ~Quadrado()
{
}

 

3) A classe que implementa o conceito de pilha (arquivo Unit3.h):

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

#ifndef Unit3H
#define Unit3H

#include "Unit2.h"      // classe Quadrado

class PilhaQuadrados
{
        private:
                class Node
                {
                        public:
                                Quadrado *itemCorrente;
                                Node *nodeAntecessor;
                        public:
                                Node( Quadrado*, Node* );        // construtor
                                ~Node( void );                         // destrutor

                };

        private:
                Node *nodeTopo;
                int qtdNodes;

        public:
                PilhaQuadrados( void );                 // construtor
                ~PilhaQuadrados( void );               // destrutor

                void Guardar( Quadrado* );
                Quadrado* Retirar( void );
                int Tamanho( void );

};

//---------------------------------------------------------------------------
#endif

 

4) E os métodos previstos para esta outra classe (arquivo Unit3.cpp):

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

#pragma hdrstop

#include "Unit3.h"     // classe PilhaQuadrados 

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

#pragma package(smart_init)

PilhaQuadrados :: PilhaQuadrados( void )                                 // construtor
{
        this->qtdNodes = 0;
        this->nodeTopo = NULL;
}
PilhaQuadrados :: ~PilhaQuadrados( void )                               // destrutor
{
        Node *nodeCorrente = this->nodeTopo,  *nodeAntecessor;
        while ( nodeCorrente != NULL ) {
                nodeAntecessor = nodeCorrente->nodeAntecessor;
                delete nodeCorrente->itemCorrente;                       // destruir quadrado corrente
                delete nodeCorrente;                                           // destruir node corrente
                nodeCorrente = nodeAntecessor;
        }
}
void PilhaQuadrados :: Guardar( Quadrado *qdr )
{
        this->nodeTopo = new Node( qdr, this->nodeTopo );
        this->qtdNodes ++;
}
Quadrado* PilhaQuadrados :: Retirar( void )
{
        Node *nodeCorrente = this->nodeTopo ;
        Quadrado *qdr = nodeCorrente->itemCorrente;
        this->nodeTopo = nodeCorrente->nodeAntecessor;
        this->qtdNodes --;
        delete nodeCorrente;
        return ( qdr );
}
int PilhaQuadrados :: Tamanho( void )
{
        return ( this->qtdNodes );
}

PilhaQuadrados :: Node :: Node( Quadrado *item, Node *no )
{
        this->itemCorrente = item;
        this->nodeAntecessor = no;
}
PilhaQuadrados :: Node :: ~Node( void )
{
}

 

5) A interface de usuário da aplicação é composta pela classe TForm1 (arquivo Unit1.h):

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

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ExtCtrls.hpp>

#include "Unit2.h"              // classe Quadrado
#include "Unit3.h"              // classe PilhaQuadrados

//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE-managed Components
        TLabel *Label1;
        TEdit *Edit1;
        TLabel *Label2;
        TEdit *Edit2;
        TLabel *Label3;
        TEdit *Edit3;
        TButton *Button1;
        TButton *Button2;
        TButton *Button3;
        TPaintBox *PaintBox1;
        TLabel *Label4;
        void __fastcall Button1Click(TObject *Sender);
        void __fastcall Button2Click(TObject *Sender);
        void __fastcall Button3Click(TObject *Sender);
        void __fastcall PaintBox1Paint(TObject *Sender);
private:    // User declarations
        Graphics::TBitmap *figura;              // bitmap
        PilhaQuadrados *minhaPilha;             // pilha

public:        // User declarations
        __fastcall TForm1(TComponent* Owner);   // construtor
        __fastcall ~TForm1(void);                       // destrutor
  void __fastcall CriarFigura(void);                    // limpar figura
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

 

6) E os métodos da classe TForm1 são definidos a seguir (arquivo Unit1.cpp):

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

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)  // construtor
{
        this->minhaPilha = new PilhaQuadrados();        // criar pilha
        this->CriarFigura();                                     // criar bitmap figura
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1(void)                             // destrutor
{
        delete this->figura;                      // destruir figura
        delete this->minhaPilha;               // destruir pilha
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)           // plotar
{
        int x, y, larg;

        x    = StrToIntDef( this->Edit1->Text, 0 );
        y    = StrToIntDef( this->Edit2->Text, 0 );
        larg = StrToIntDef( this->Edit3->Text, 0 );

        Quadrado *qdr;                                 // declarar ponteiro de quadrado
        qdr =  new Quadrado( x, y, larg );        // instanciar quadrado
        qdr->Plotar( this->figura );                 // plotar no bitmap

        this->PaintBox1->Refresh();               // refazer paintbox

        this->minhaPilha->Guardar( qdr );       // guardar quadrado na pilha

        this->Label4->Caption = "Qtd.Quadrados: " +
                                IntToStr( this->minhaPilha->Tamanho() );
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button2Click(TObject *Sender)           // limpar
{
        delete this->figura;                 // deletar figura atual
        this->CriarFigura();                 // criar nova figura
        this->PaintBox1->Refresh();     // refazer paintbox
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button3Click(TObject *Sender)           // refazer tudo
{
        // criar uma nova pilha

        PilhaQuadrados *pilhaInvertida = new PilhaQuadrados();

        while ( this->minhaPilha->Tamanho() > 0 )
        {
                // obter quadrado do topo da pilha

                Quadrado *tmp = this->minhaPilha->Retirar();

                // plotar quadrado

                tmp->Plotar( this->figura );

                // guardar quadrado na nova pilha

                pilhaInvertida->Guardar( tmp );

                // refazer paintbox

                this->PaintBox1->Refresh();

                // aguardar 500ms

                Sleep( 500 );
        }

        // destruir pilha velha

        delete this->minhaPilha;

        // copiar referencia da nova pilha para a velha

        this->minhaPilha = pilhaInvertida;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::PaintBox1Paint(TObject *Sender)   // refazer paintbox
{
        // exibir bitmap no paintbox

        this->PaintBox1->Canvas->Draw( 0, 0, this->figura );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CriarFigura()                    // criar bitmap
{
        this->figura = new Graphics::TBitmap();

        // redimensionar largura e altura

        this->figura->Width = this->PaintBox1->Width ;
        this->figura->Height = this->PaintBox1->Height;
}
//---------------------------------------------------------------------------

 

Até  próxima.

sexta-feira, 11 de abril de 2008

Borland C++ Builder - Dicas sobre compilação e criação de aplicações

 

Ao criar uma aplicação para ser executada em outro computador que não disponha dos pacotes e bibliotecas do tipo "run-time", convém configurar as opções do projeto antes de sua compilação.

No menu principal -> Project -> Options... , desmarcar a opção "Use dynamic RTL" da aba "Linker":

project_options1

E da aba "Packages", desmarcar a opção "Build with runtime packages":

project_options2

Agora é só recompilar a aplicação e distribuir o executável para ser usado em outros computadores.

Esta dica foi baseada no texto do link:

http://www.functionx.com/bcb/sockets/socket.htm

Até mais.

sábado, 5 de abril de 2008

Plotando gráficos no MS VS2005 C++

 

Vamos à versão no C++ do MS VS2005, começando com a interface gráfica e o destaque da referência ao evento "button1_Click":

 

image

 

Aqui é destacada a referência ao evento "pictureBox1_Paint":

 

image

 

Começando pelo código da classe Quadrado através do arquivo "Quadrado.h":

 

ref class Quadrado
{
        private:
                int x;
                int y;
                int largura;

        public:
                Quadrado();                                    // construtor default
                Quadrado( int, int );                        // construtor
                Quadrado( int, int, int );                    // construtor

                void Plotar( System::Drawing::Graphics^ );

                ~Quadrado();                                // destrutor
};

 

O código para o arquivo "Quadrado.cpp":

 

#include "stdafx.h"

#include "Quadrado.h"

Quadrado :: Quadrado( )                               // construtor default
{
        this->x = 100;
        this->y = 200;
        this->largura = 90;
}

Quadrado :: Quadrado( int a, int b )                 // construtor
{
        this->x = a;
        this->y = b;
        this->largura = 50;
}

Quadrado :: Quadrado( int a, int b, int c)           // construtor
{
        this->x = a;
        this->y = b;
        this->largura = c;
}

void Quadrado :: Plotar( System::Drawing::Graphics^ tmp )
{
        // cor e espessura para a caneta

        System::Drawing::Pen ^caneta = gcnew System::Drawing::Pen 
                                                              (
System::Drawing::Color::Red, 1 );

        tmp->DrawLine( caneta,
                              this->x, this->y,                                             // ponto (x1, y1)
                              this->x + this->largura, this->y  );                     // ponto (x2, y2)

        tmp->DrawLine( caneta,
                              this->x + this->largura, this->y,                         // ponto (x2, y2)
                              this->x + this->largura, this->y + this->largura );  // ponto (x3, y3)

        tmp->DrawLine( caneta,
                              this->x + this->largura, this->y + this->largura,    // ponto (x3, y3)
                              this->x, this->y + this->largura );                      // ponto (x4, y4)

        tmp->DrawLine( caneta,
                              this->x, this->y + this->largura,                         // ponto (x4, y4)
                              this->x, this->y );                                           // ponto (x1, y1)

        delete caneta;
}

Quadrado :: ~Quadrado()
{
}

E o principal, o código da classe do formulário (renomeado para "Plotador.h"):

#pragma once

#include "Quadrado.h"

namespace ClasseQuadrado {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for Plotador
    ///
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>

    public ref class Plotador : public System::Windows::Forms::Form
    {

    private:

             System::Drawing::Bitmap^    figura;
             System::Drawing::Graphics^ quadro;

    public:

        Plotador(void)
        {
            InitializeComponent();

            //
            //TODO: Add the constructor code here
            //

            this->figura = gcnew System::Drawing::Bitmap( this->pictureBox1->Width,
                                                                             this->pictureBox1->Height );

            this->quadro = System::Drawing::Graphics::FromImage( this->figura );

            this->quadro->Clear( Color::White );

        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>

        ~Plotador()
        {

            if (components)
            {
                delete components;
            }

            delete this->figura;

        }

    private: System::Windows::Forms::Label^  label1;
    private: System::Windows::Forms::Label^  label2;
    private: System::Windows::Forms::Label^  label3;
    private: System::Windows::Forms::Button^  button1;
    private: System::Windows::Forms::TextBox^  textBox1;
    private: System::Windows::Forms::TextBox^  textBox2;
    private: System::Windows::Forms::TextBox^  textBox3;
    private: System::Windows::Forms::PictureBox^  pictureBox1;

    private:

        /// <summary>
        /// Required designer variable.
        /// </summary>

        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>

        void InitializeComponent(void)
        {
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->label3 = (gcnew System::Windows::Forms::Label());
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->textBox1 = (gcnew System::Windows::Forms::TextBox());
            this->textBox2 = (gcnew System::Windows::Forms::TextBox());
            this->textBox3 = (gcnew System::Windows::Forms::TextBox());
            this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  
                                                                       >(this->pictureBox1))->BeginInit();
            this->SuspendLayout();
            //
            // label1
            //
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(12, 9);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(14, 13);
            this->label1->TabIndex = 0;
            this->label1->Text = L"X";
            //
            // label2
            //
            this->label2->AutoSize = true;
            this->label2->Location = System::Drawing::Point(95, 9);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(14, 13);
            this->label2->TabIndex = 1;
            this->label2->Text = L"Y";
            //
            // label3
            //
            this->label3->AutoSize = true;
            this->label3->Location = System::Drawing::Point(178, 9);
            this->label3->Name = L"label3";
            this->label3->Size = System::Drawing::Size(43, 13);
            this->label3->TabIndex = 2;
            this->label3->Text = L"Largura";
            //
            // button1
            //
            this->button1->Location = System::Drawing::Point(290, 4);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(57, 23);
            this->button1->TabIndex = 3;
            this->button1->Text = L"Plotar";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &Plotador::button1_Click);
            //
            // textBox1
            //
            this->textBox1->Location = System::Drawing::Point(32, 6);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(57, 20);
            this->textBox1->TabIndex = 4;
            //
            // textBox2
            //
            this->textBox2->Location = System::Drawing::Point(115, 6);
            this->textBox2->Name = L"textBox2";
            this->textBox2->Size = System::Drawing::Size(57, 20);
            this->textBox2->TabIndex = 5;
            //
            // textBox3
            //
            this->textBox3->Location = System::Drawing::Point(227, 6);
            this->textBox3->Name = L"textBox3";
            this->textBox3->Size = System::Drawing::Size(57, 20);
            this->textBox3->TabIndex = 6;
            //
            // pictureBox1
            //
            this->pictureBox1->Location = System::Drawing::Point(10, 34);
            this->pictureBox1->Name = L"pictureBox1";
            this->pictureBox1->Size = System::Drawing::Size(540, 369);
            this->pictureBox1->TabIndex = 7;
            this->pictureBox1->TabStop = false;
            this->pictureBox1->Paint += gcnew System::Windows::Forms::PaintEventHandler
                                                                 (this, &Plotador::pictureBox1_Paint);
            //
            // Plotador
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(558, 412);
            this->Controls->Add(this->pictureBox1);
            this->Controls->Add(this->textBox3);
            this->Controls->Add(this->textBox2);
            this->Controls->Add(this->textBox1);
            this->Controls->Add(this->button1);
            this->Controls->Add(this->label3);
            this->Controls->Add(this->label2);
            this->Controls->Add(this->label1);
            this->Name = L"Plotador";
            this->Text = L"Plotador de Quadrados";
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  
                                                                    
>(this->pictureBox1))->EndInit();
            this->ResumeLayout(false);
            this->PerformLayout();

        }

#pragma endregion

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
             {

                Quadrado ^q1, ^q2, ^q3;

                q1 =  gcnew Quadrado();
                q1->Plotar( this->quadro );

                q2 =  gcnew Quadrado( 400, 100 );
                q2->Plotar( this->quadro );

                q3 =  gcnew Quadrado( 50, 50, 20);
                q3->Plotar( this->quadro );

                this->pictureBox1->Refresh() ;

                delete q1;
                delete q2;
                delete q3;

             }

private: System::Void pictureBox1_Paint(System::Object^  sender,
                                                       System::Windows::Forms::PaintEventArgs^  e)
            {
                e->Graphics->DrawImage( this->figura, 0, 0 );        // bitmap e ponto(x, y)
            }

    };    // class

} // namespace

 

E para encerrar, a saída da execução:

 

image

 

Como também na versão C++ Builder, fica faltando complementar o código com as instruções para plotar o quadrado desejado conforme sua localização e largura indicadas.

 

Até mais.

Links de interesse em Borland C++ Builder

Vale a pena dar uma olhada nos sites:

http://www.dicasbcb.com.br/Mapa.html

http://www.dicasbcb.com.br/Curso.html

http://www.macsystemeduc.com.br/livros/builder.html

http://www.functionx.com/

http://www.functionx.com/bcb/

 

Bom estudo e até mais.

Plotando gráficos no Borland C++ Builder

 

Convém praticar o desenvolvimento do projeto "Desenhando em Cpp Builder" publicado em:


 http://www.cbrasil.org/wiki/index.php?title=Desenhando_em_Cpp_Builder, por Wanderley Caloni.


No projeto acima são abordados os conceitos básicos para plotagem de elementos gráficos diretamente na região de um formulário (objeto Form1 instanciado da classe TForm1) e a persistência e reconstituição dos elementos plotados quando o formulário é redesenhado ao retomar o foco do gerenciador de janelas (evento FormPaint).

Toda a lógica está orientada aos eventos:

  • FormMouseDown: fixar a posição da caneta para plotagem de linha (Canvas->PenPos) relativa à posição corrente do mouse;
  • FormMouseMove: traçar linha até o ponto relativo à posição corrente do mouse;
  • FormMouseUp: desligar flag (mouseDown) que controla a plotagem;
  • FormPaint: reconstituir a plotagem quando o formulário retoma o foco do gerenciador de janelas;

A classe TForm1 (Form1), por herança da classe TForm, agrega a classe TCanvas (definida na biblioteca Graphics.hpp). O objeto canvas do formulario disponibiliza diversos métodos e propriedades para plotagem gráfica:

  • Canvas->PenPos : fixar a posição da caneta para plotagem de linha em um ponto (x1, y1);
  • Canvas->LineTo : traçar linha do ponto (x1, y1) até um ponto (x2, y2), deixando a caneta nesta nova posição;
  • Canvas->Draw : plotar um objeto do tipo bitmap (de área retangular) a partir do canto superior esquerdo deste na posição inicial definida pelo ponto (x, y) ;

Objetos da classe Graphics::TBitmap também disponibizam um canvas, permitindo construir todo um conteúdo a ser plotado primeiramente em formato bitmap e, numa etapa posterior, poderemos usar estes bitmaps para plotar em objetos como formulario (TForm), paintbox (TPaintPox) , image (TImage) e até mesmo em outro objeto bitmap (TBitmap).

A partir do projeto do Wanderley Caloni, foi desenvolvida uma versão usando a classe Graphics::TBitmap (graphics.hpp) e, para reforçar os conceitos de orientação a objetos, foi proposta a construção de uma classe denominada Quadrado para realizar a plotagem das arestas de quadrados desejados diretamente em um bitmap.

Começando pela interface gráfica do projeto, temos:

image

 

Destacamos os seguintes eventos para tratamento "PaintBox1Paint":

image

e "Button1Click":

image

 

O código para o "Unit1.h" do formulário ficou assim:

 

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

#ifndef Unit1H
#define Unit1H

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

#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ExtCtrls.hpp>

#include "Unit2.h"

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

class TForm1 : public TForm
{
__published:    // IDE-managed Components

        TLabel *Label1;
        TEdit *Edit1;
        TLabel *Label2;
        TEdit *Edit2;
        TLabel *Label3;
        TEdit *Edit3;
        TButton *Button1;
        TPaintBox *PaintBox1;

        void __fastcall Button1Click(TObject *Sender);
        void __fastcall PaintBox1Paint(TObject *Sender);

private:    // User declarations

        Graphics::TBitmap *figura;

public:        // User declarations

        __fastcall TForm1(TComponent* Owner);       // construtor
        __fastcall ~TForm1( void );                         // destrutor

};

//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------

#endif

 

E aqui o código para o "Unit1.cpp":

 

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

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"

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

#pragma package(smart_init)
#pragma resource "*.dfm"

TForm1 *Form1;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)  // construtor
{
        this->figura = new Graphics::TBitmap();

        this->figura->Width = this->PaintBox1->Width ;
        this->figura->Height = this->PaintBox1->Height;

}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()                                                   // destrutor
{
        delete this->figura;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)


       
// Os valores fornecidos para X, Y e L não foram considerados nesta
        // versão preliminar, apenas para mostrar o uso de
        // múltiplos construtores da classe Quadrado.

        Quadrado *q1, *q2, *q3;

        q1 =  new Quadrado();
       
q1->Plotar( this->figura );
       

q2 =  new Quadrado( 400, 100 );
q2->Plotar( this->figura );


q3 =  new Quadrado( 50, 50, 20);
q3->Plotar( this->figura );

        this->PaintBox1->Repaint() ;

        delete q1;
        delete q2;
        delete q3;

}
//---------------------------------------------------------------------------

void __fastcall TForm1::PaintBox1Paint(TObject *Sender)
{
        this->PaintBox1->Canvas->Draw( 0, 0, this->figura );
}
//---------------------------------------------------------------------------

 

E agora o código para a classe Quadrado, começando pelo "Unit2.h":

 

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

#ifndef Unit2H
#define Unit2H

#include <graphics.hpp>

class Quadrado
{
        private:

                int x;
                int y;
                int largura;

        public:

                Quadrado();                                       // construtor default
                Quadrado( int, int );                            // construtor
                Quadrado( int, int, int );                       // construtor

                void Plotar( Graphics::TBitmap * );

                ~Quadrado();                                    // destrutor

};

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

#endif

 

E finalmente o "Unit2.cpp" para a classe Quadrado:

 

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

#pragma hdrstop

#include "Unit2.h"

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

#pragma package(smart_init)

Quadrado :: Quadrado( )                               // construtor default
{
        this->x = 100;
        this->y = 200;
        this->largura = 90;
}

Quadrado :: Quadrado( int a, int b )                 // construtor
{
        this->x = a;
        this->y = b;
        this->largura = 50;
}

Quadrado :: Quadrado( int a, int b, int c)           // construtor
{
        this->x = a;
        this->y = b;
        this->largura = c;
}

void Quadrado :: Plotar( Graphics::TBitmap *tmp )
{
        tmp->Canvas->PenPos = TPoint( this->x, this->y );

        tmp->Canvas->LineTo( this->x + this->largura, this->y  );

        tmp->Canvas->LineTo( this->x + this->largura, this->y + this->largura );

        tmp->Canvas->LineTo( this->x, this->y + this->largura  );

        tmp->Canvas->LineTo( this->x, this->y  );

}

Quadrado :: ~Quadrado()
{
}

 

E então, aqui temos a execução do programa quando do clique no botão Plotar:

 

image

 

Próxima tarefa: complementar o código que falta para plotar o quadrado conforme localização e largura indicadas.

 

Até mais.