Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill custom area with color

How can I fill a selected area with color?

var Rect: TRect;
    Color: TColor;
begin
  //fill area with color
end;
like image 828
Little Helper Avatar asked Nov 27 '11 17:11

Little Helper


2 Answers

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.

like image 128
David Heffernan Avatar answered Nov 20 '22 11:11

David Heffernan


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).

like image 4
Jerry Dodge Avatar answered Nov 20 '22 11:11

Jerry Dodge