Fill custom area with color
Asked Answered
P

2

7

How can I fill a selected area with color?

var Rect: TRect;
    Color: TColor;
begin
  //fill area with color
end;
Parodist answered 27/11, 2011 at 17:36 Comment(0)
A
10

You have not stated what you mean by custom area and you talk about a "selected area". I don't know what you mean.

For a simple rectangle then you typically would fill the rectangle with TCanvas.FillRect.

Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := Color;
Canvas.FillRect(R);

where R is a TRect specifying the rectangle.

For a more complex region then you need to fall back on the Windows GDI function FillRgn. This function is not wrapped by TCanvas but you can simply call it passing TCanvas.Handle as the HDC.

Airsick answered 27/11, 2011 at 17:42 Comment(2)
And just to add, for non-rectangular area I'd suggest ExtFloodFill functionRoddy
@Magicmaster I didn't think of that. It's a good suggestion though. Flood fill is a bit different from FillRect/FillRgn but could be appropriate here.Airsick
S
4

You need to be a LOT more specific, but this should get you going in the right direction:

procedure DoMyDrawing(Canvas: TCanvas; L, T, R, B: Integer; Color: TColor);
var
  Rec: TRect;
begin
  Rec.Left:= L;
  Rec.Top:= T;
  Rec.Right:= R;
  Rec.Bottom:= B;
  //SAME AS Rec:= Rect(L, T, R, B);
  Canvas.Brush.Color:= Color;
  Canvas.Brush.Style:= bsSolid;
  Canvas.Pen.Style:= psClear;
  Canvas.FillRect(Rec);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  DoMyDrawing(Self.Canvas, 10, 10, 50, 50, clNavy);
end;

EDIT:

I would more-so recommend using a TRect instead of the 4 coordinates (Left, Top, Right, and Bottom) because a TRect includes all 4 of those already. You can also read a TRect with a TopLeft TPoint and a BottomRight TPoint.

(I also fixed a typo above - Canvas.FillRect(R); was supposed to be Canvas.FillRect(Rec);)

Here's another version of the same procedure:

procedure DoMyDrawing(Canvas: TCanvas; const R: TRect; const Color: TColor);
begin
  Canvas.Brush.Color:= Color;
  Canvas.Brush.Style:= bsSolid;
  Canvas.Pen.Style:= psClear;
  Canvas.FillRect(R);
end;

Much easier, isn't it?


ANOTHER EDIT:

Also note the function I'm using Rect(Left, Top, Right, Bottom) - This makes things simple too. Unfortunately I've seen some standard VCL controls which have events with parameters named Rect: TRect; which messes up the ability to use the original function in the classes unit. So also avoid using a variable with the name Rect because it will prevent you from being able to use the Rect function (which turns 4 lines of code into just 1).

Sumikosumma answered 27/11, 2011 at 17:59 Comment(2)
I also recommend instead of using 4 numbers (Left, Top, Right, Bottom), use TRect instead, which is all 4 already combined together.Sumikosumma
Rather than commenting on your own answer, you can just edit it. It's a wiki. In fact anyone can edit your answer.Airsick

© 2022 - 2024 — McMap. All rights reserved.