由于TPanel没有Canvas属性,属于其自身维护了其绘制的功能,要在其上画图,需要重载它的WM_PAINT消息。
//.h文件
class TForm1 : public TForm
{
__published: // IDE-managed Components
TPanel *Panel1;
TButton *Button1;
private: // User declarations
TWndMethod FPanelWndProc;
void __fastcall PanelWndProc(TMessage& Message);
public: // User declarations
__fastcall TForm1(TComponent* Owner);
virtual __fastcall ~TForm1();
};
//,cpp文件
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
// remember the panel 's original window procedure
FPanelWndProc = Panel1-> WindowProc;
// subclass the panel
Panel1-> WindowProc = PanelWndProc;
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()
{
// restore the panel 's original window procedure
Panel1-> WindowProc = FPanelWndProc;
FPanelWndProc = NULL;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::PanelWndProc(TMessage& Message)
{
FPanelWndProc(Message);
// do your own painting
if (Message.Msg == WM_PAINT)
{
// Graphics::TBitmap *bit = new Graphics::TBitmap;
// bit->Assign(Image1->Picture->Graphic);
// HDC hDC = GetDC(Panel1->Handle);
// StretchBlt(hDC,0,0,Panel1->Width,Panel1->Height,bit->Canvas->Handle,
// 0,0,bit->Width,bit->Height,SRCCOPY);
// delete bit;
float Step;
TRect BandRect;
//A panel doesn 't have a canvas property. Create one.
TControlCanvas *PanelCanvas=new TControlCanvas;
PanelCanvas-> Control=Panel1;
Step=(float)Panel1-> ClientHeight/256; //256 bandes de couleur
for(int i=0;i <256;i++)
{
BandRect.Left=0;
BandRect.Top=(int)(i*Step);
BandRect.Right=Panel1-> ClientWidth+1;
BandRect.Bottom=(int)((i+1)*Step); // bandes horizontales
PanelCanvas-> Brush-> Color=RGB(0,0,255-i); // bandes bleues
PanelCanvas-> FillRect(BandRect);
}
delete PanelCanvas;
}
}