{-------------------------------------------------------------------------------
Demonstrates drawing a vertical and horizontal gradient in a rectangle.
-------------------------------------------------------------------------------}
{$mode objfpc}{$h+}
program project1;
uses
Classes, Types,
FPImage, FPCanvas, FPImgCanv, FPWritePNG;
type
TGradientDir = (gdHorizontal, gdVertical);
procedure GradientFill(Canvas: TFPCustomCanvas; ARect: TRect;
AStartColor, AEndColor: TFPColor; ADirection: TGradientDir);
function InterpolateColor(x, xmax: Integer): TFPColor;
var
factor1, factor2: Single;
begin
factor2 := x / xmax;
factor1 := 1.0 - factor2;
Result.Red := trunc(AStartColor.Red * factor1 + AEndColor.Red * factor2);
Result.Green := trunc(AStartColor.Green * factor1 + AEndColor.Green * factor2);
Result.Blue := trunc(AStartColor.Blue * factor1 + AEndColor.Blue * factor2);
Result.Alpha := trunc(AStartColor.Alpha * factor1 + AEndColor.Alpha * factor2);
end;
var
x, y, xmax, ymax: Integer;
color: TFPColor;
begin
if ADirection = gdHorizontal then
begin
xmax := ARect.Right - ARect.Left;
for x := ARect.Left to ARect.Right do
begin
color := InterpolateColor(x - ARect.Left, xmax);
for y := ARect.Top to ARect.Bottom do
Canvas.DrawPixel(x, y, color);
end;
end else
begin
ymax := ARect.Bottom - ARect.Top + 1;
for y := ARect.Top to ARect.Bottom do
begin
color := InterpolateColor(y - ARect.Top, ymax);
for x := ARect.Left to ARect.Right do
Canvas.DrawPixel(x, y, color);
end;
end;
end;
var
image: TFPCustomImage;
canvas: TFPImageCanvas;
R: TRect;
begin
image := TFPMemoryImage.Create(400, 200);
try
canvas := TFPImageCanvas.Create(image);
try
// Horizontal gradient
R := Rect(10, 10, 195, 190);
canvas.Brush.Style := bsClear;
canvas.Pen.FPColor := colWhite;
canvas.Rectangle(R);
InflateRect(R, -1, -1);
GradientFill(canvas, R, colRed, colYellow, gdHorizontal);
// Vertical gradient
R := Rect(205, 10, 390, 190);
canvas.Pen.FPColor := colWhite;
canvas.Rectangle(R);
InflateRect(R, -1, -1);
GradientFill(canvas, R, colBlue, colSilver, gdVertical);
// Save to file
image.SaveToFile('Gradient_Test.png');
finally
canvas.Free;
end;
finally
image.Free;
end;
end.