Mega Code Archive
 
 
    
Bitmap to HRGN
Title: Bitmap to HRGN
Question: How do I create a region from a mask bitmap?
Answer:
Use this function to create a HRGN from a black and white bitmap. All black pixels are in the region, the white are "transparents". It could be easily changed to allow all colors and choose one to be transparent.
You are responsible of releasing the region when you are finished with it with the function DeleteObject.
A popular usage of Regions is with the function SetWindowRgn to change the shape of a control. In that case, you do not free the region since it is owned by the operating system after the call. Look at my article ID #517 for an example of that.
function BitmapToRgn(Image: TBitmap): HRGN;
var
 TmpRgn: HRGN;
 x, y: integer;
 ConsecutivePixels: integer;
 CurrentPixel: TColor;
 CreatedRgns: integer;
 CurrentColor: TColor;
begin
 CreatedRgns := 0;
 Result := CreateRectRgn(0, 0, Image.Width, Image.Height);
 inc(CreatedRgns);
 if (Image.Width = 0) or (Image.Height = 0) then exit;
 for y := 0 to Image.Height - 1 do
 begin
 CurrentColor := Image.Canvas.Pixels[0,y];
 ConsecutivePixels := 1;
 for x := 0 to Image.Width - 1 do
 begin
 CurrentPixel := Image.Canvas.Pixels[x,y];
 if CurrentColor = CurrentPixel
 then inc(ConsecutivePixels)
 else begin
 // We are entering a new zone
 if CurrentColor = clWhite then
 begin
 TmpRgn := CreateRectRgn(x-ConsecutivePixels, y, x, y+1);
 CombineRgn(Result, Result, TmpRgn, RGN_DIFF);
 inc(CreatedRgns);
 DeleteObject(TmpRgn);
 end;
 CurrentColor := CurrentPixel;
 ConsecutivePixels := 1;
 end;
 end;
 if (CurrentColor = clWhite) and (ConsecutivePixels 0) then
 begin
 TmpRgn := CreateRectRgn(x-ConsecutivePixels, y, x, y+1);
 CombineRgn(Result, Result, TmpRgn, RGN_DIFF);
 inc(CreatedRgns);
 DeleteObject(TmpRgn);
 end;
 end;
end;