4

What is the fastest way of getting the area of any arbitrary Windows region?

I know I can enumerate all points of bounding rectangle and call the PtInRegion() function but it seems not very fast. Maybe you know some faster way?

Ondrej Kelle
  • 36,941
  • 2
  • 65
  • 128
Andrew
  • 3,696
  • 3
  • 40
  • 71
  • 2
    Probably [`GetRegionData`](http://msdn.microsoft.com/en-us/library/windows/desktop/dd144920(v=vs.85).aspx) and use the points to calculate the area of a polygon – Seth Carnegie Jul 18 '12 at 14:17

1 Answers1

10

When you call GetRegionData, you'll get a list of non-overlapping rectangles that make up the region. Add up their areas, something like this:

function GetRegionArea(rgn: HRgn): Cardinal;
var
  x: DWord;
  Data: PRgnData;
  Header: PRgnDataHeader;
  Rects: PRect;
  Width, Height: Integer;
  i: Integer;
begin
  x := GetRegionData(rgn, 0, nil);
  Win32Check(x <> 0);
  GetMem(Data, x);
  try
    x := GetRegionData(rgn, x, Data);
    Win32Check(x <> 0);
    Header := PRgnDataHeader(Data);
    Assert(Header.iType = rdh_Rectangles);

    Assert(Header.dwSize = SizeOf(Header^));
    Rects := PRect(Cardinal(Header) + Header.dwSize);
    // equivalent: Rects := PRect(@Data.Buffer);

    Result := 0;
    for i := 0 to Pred(Header.nCount) do begin
      Width := Rects.Right - Rects.Left;
      Height := Rects.Bottom - Rects.Top;
      Inc(Result, Width * Height);
      Inc(Rects);
    end;
  finally
    FreeMem(Data);
  end;
end;
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467