分类: C/C++
2008-05-31 09:28:25
在Form1的OnCreate事件中添加:
void __fastcall TForm1::FormCreate(TObject *Sender)
{
BmpToRgn();
}
在.h文件中的private段中添加
void __fastcall TForm1::BmpToRgn();
这个函数用来创建不规则窗体。
//---------------------------------------
void __fastcall TForm1::BmpToRgn()
{
Image1->AutoSize=true;
Form1->AutoSize=true;
Form1->BorderStyle=bsNone; //将Form的标题栏去掉
TColor ColorKey=Image1->Canvas->Pixels[0][0]; //以这个点的颜色为透明基准色
int x,y;
int l,r;
POINT *a;
bool lb,rb;
HRGN wndrgn,temprgn;
if((a=(POINT *)malloc(Width*2*(sizeof(POINT))))==NULL)
{
ShowMessage(\"申请内存失败!\");
exit(0);
}
l=0;r=Image1->Height*2-1;
wndrgn=CreateRectRgn(0,0,Image1->Width,Image1->Height);
for(y=0;y
{
lb=true;
for(x=0;x
if(Image1->Canvas->Pixels[x][y]!=ColorKey)
{
a[l].x=x;
a[l].y=y;
lb=false;
break;
}
if(lb) a[l]=a[l-1];
l++;
rb=true;
for(x=Image1->Width;x>=0;x--)
if(Image1->Canvas->Pixels[x][y]!=ColorKey)
{
a[r].x=x;
a[r].y=y;
rb=false;
break;
}
if(rb) a[r]=a[r+1];
r--;
}
r=Image1->Height*2-1;
for(y=0;y
{
for(x=a[y].x;x<=a[r].x;x++)
if(Image1->Canvas->Pixels[x][y]==ColorKey)
{
temprgn=CreateRectRgn(x,y,x+1,y+1);
CombineRgn(wndrgn,wndrgn,temprgn,RGN_XOR);
DeleteObject(temprgn);
}
r--;
}
//temprgn=CreatePolygonRgn(a,Image1->Height*2,ALTERNATE);
temprgn=CreatePolygonRgn(a,Image1->Height*2,WINDING);
CombineRgn(wndrgn,wndrgn,temprgn,RGN_AND);
DeleteObject(temprgn);
delete a;
SetWindowRgn(Handle,wndrgn,true);
}
为了使没有标题栏的窗体能移动,需要在Image1的OnMouseDown事件中添加以下代码:
void __fastcall TForm1::Image1MouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if(Button == mbLeft)
{
ReleaseCapture();
Perform(WM_NCLBUTTONDOWN,HTCAPTION, 0);
}
}
//-----------------------------------------
//通过右键菜单中的Exit1退出程序
void __fastcall TForm1::Exit1Click(TObject *Sender)
{
Close();
}
//---------------------------------------
//打开图片文件,并以这个图片创建不规则窗体
void __fastcall TForm1::Open1Click(TObject *Sender)
{
if(OpenPictureDialog1->Execute())
{
Image1->Picture->LoadFromFile(OpenPictureDialog1->FileName);
BmpToRgn();
}
}
注意图片的背景色要相同。