Search code examples
delphidelphi-xe2

I want to draw 2 rectangles that superimpose on one another with Windows.FillRect


I want to draw 2 rectangles that superimpose on one another. One of which I want it a smaller size(A) than the other one (B) so that I can view the one at the back(B).

A is in Black and B is in aqua colour

procedure DrawRectangle(drawDC:HDC;cellBrush:TBrush);
var
    gridCellRect, gridCellRect1  :Trect ;   
begin
    gridCellRect.Top := 75;
    gridCellRect.Bottom := 150;
    gridCellRect.Left  := 192;
    gridCellRect.right := 200; 
    SetBkMode(drawDC, OPAQUE);
    cellBrush.color := claqua;

    Windows.FillRect(DrawDC, gridCellRect, cellBrush.Handle);

    gridCellRect1 := gridCellRect;
    // I tried to modify the top position to make it visible
    gridCellRect1.Top := gridCellRect -5; 
    cellBrush.color := clBlack;
    Windows.FillRect(DrawDC, gridCellRect, cellBrush.Handle);
end;

Solution

  • You've got your colors reversed (you're drawing in the wrong order), your gridCellRect.Left and gridCellRect.Right are far too narrow (8 pixels), and you don't need the call to SetBkMode at all.

    In addition, you've got an error in gridCellRect - 5 (which won't even compile), and you never try to draw to the rectangle defined in gridCellRect1 even if it did. (Your second call to FillRect uses gridCellRect instead of gridCellRect1.)

    Here's a corrected version of the code that should get you started:

    procedure DrawRectangle(drawDC:HDC;cellBrush:TBrush);
    var
      gridCellRect, gridCellRect1  :Trect ;
    begin
      gridCellRect.Top := 75;
      gridCellRect.Bottom := 150;
      gridCellRect.Left  := 125;    // Changed left and right to widen
      gridCellRect.right := 200;
      cellBrush.color := clBlack;
      Windows.FillRect(DrawDC, gridCellRect, cellBrush.Handle);
    
      gridCellRect1 := gridCellRect;
      gridCellRect1.Top := gridCellRect.Top + 5;
      gridCellRect1.Bottom := gridCellRect.Bottom - 5;
      cellBrush.color := clAqua;
      Windows.FillRect(DrawDC, gridCellRect1, cellBrush.Handle);
    end;
    

    Tested with

    procedure TForm1.FormPaint(Sender: TObject);
    begin
      DrawRectangle(Canvas.Handle, Canvas.Brush);
    end;