以下代码可以根据一个BMP图片绘制一个任意形状的窗体,不仅是椭圆形。
BMP图片可以随便用PhotoShop或者画笔画一个。
CreateRegion函数稍做修改,就可以不要BMP图片。
---------------------------------------------------------------------------
function Tform1.CreateRegion(wMask:TBitmap;wColor:TColor;hControl:THandle): HRGN;
var
dc, dc_c: HDC;
rgn: HRGN;
x, y: integer;
coord: TPoint;
line: boolean;
color: TColor;
begin
dc := GetWindowDC(hControl); //取得窗口的DC
dc_c := CreateCompatibleDC(dc);
SelectObject(dc_c, wMask.Handle);
BeginPath(dc);//开始绘制
for x:=0 to wMask.Width-1 do //设定窗体的大小和形状
begin
line := false;
for y:=0 to wMask.Height-1 do
begin
color := GetPixel(dc_c, x, y);
if not (color = wColor) then
begin
if not line then
begin
line := true;
coord.x := x;
coord.y := y;
end;
end;
if (color = wColor) or (y=wMask.Height-1) then
begin
if line then
begin
line := false;
MoveToEx(dc, coord.x, coord.y, nil);
LineTo(dc, coord.x, y);
LineTo(dc, coord.x + 1, y);
LineTo(dc, coord.x + 1, coord.y);
CloseFigure(dc);
end;
end;
end;
end;
EndPath(dc);//结束绘制
rgn := PathToRegion(dc);
ReleaseDC(hControl, dc); //释放DC
Result := rgn;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
w1:TBitmap;
w2:TColor;
rgn: HRGN;
begin
w1:=TBitmap.Create;
w1.Assign(image1.Picture.Bitmap);//取得图片对象
w2:=w1.Canvas.Pixels[0,0];
rgn := CreateRegion(w1,w2,Handle);//生成窗体区域
if rgn<>0 then
begin
SetWindowRgn(Handle, rgn, true);//设定窗体形状
end;
w1.Free;
end;