Categories
Delphi

A routine for painting tiled / stretched images to a canvas

If you want to paint a tiled image to a canvas, this routine will do it.

ACanvas – the canvas to paint to
ARect – A TRect of the area to paint to
Offset – A TPoint which specifies the origin that the images should start from. Usually Point(0,0)
AnImage – Any TGraphic
AMode – No Tile, Tile across, Tile down, Tile both, Stretch to Rect
AColor – sets the rect to this color first. – this is best used when using a transparent graphic format such as png or gif


type
	TZ9TileMode = (pmNoRepeat, pmRepeatX, pmRepeatY, pmRepeatXY, pmFitXY );

procedure PaintBackground(ACanvas : TCanvas; ARect : TRect; Offset : TPoint; AnImage : TGraphic; AMode : TZ9TileMode; BGColor : TColor);
var
	x, y : integer;
begin
	if (AnImage is TPNGObject) then
	begin
		ACanvas.Brush.Color := BGColor;
		ACanvas.FillRect(ARect);
	end;
	if (AnImage.Width = 0) or (AnImage.Height = 0) then exit;
	
	case Amode of
	pmRepeatXY :
		begin
			y := Offset.Y;
			while y <= Arect.Bottom do
			begin
				x := Offset.X;
				while x <= Arect.Right do
				begin
					ACanvas.Draw(x,y,AnImage);
					inc(x, AnImage.Width);
				end;
				inc(y, AnImage.Height)
			end;
		end;
	pmRepeatX :
		begin
			y := Offset.Y;
			x := Offset.X;
			while x <= Arect.Right do
			begin
				ACanvas.Draw(x,y,AnImage);
				inc(x, AnImage.Width);
			end;
			ACanvas.Brush.Color := BGColor;
			ACanvas.FillRect( Rect(ARect.Left,y+AnImage.Height,ARect.Right,ARect.Bottom));
		end;
	pmRepeatY :
		begin
			x := Offset.X;
			y := Offset.Y;
			while y <= Arect.Bottom do
			begin
				ACanvas.Draw(x,y,AnImage);
				inc(y, AnImage.Height)
			end;
			ACanvas.Brush.Color := BGColor;
			ACanvas.FillRect( Rect(x + AnImage.width,ARect.top,ARect.Right,ARect.Bottom));
		end;
	pmNoRepeat :
		begin
			x := Offset.X;
			y := Offset.Y;
			ACanvas.Draw(x,y,AnImage);
			ACanvas.Brush.Color := BGColor;
			ACanvas.FillRect( Rect(X+AnImage.width,y+AnImage.Height,ARect.Right,ARect.Bottom));
			ACanvas.FillRect( Rect(ARect.left,y+AnImage.Height,X+AnImage.width,ARect.Bottom));
			ACanvas.FillRect( Rect(X+AnImage.Width,ARect.Top,ARect.Right,y+AnImage.Height));
		end;
	pmFitXY :
		begin
			x := Offset.X;
			y := Offset.Y;
			ACanvas.StretchDraw(Rect(x,y,x + (ARect.Right-ARect.left), y + (ARect.bottom-ARect.top) ),AnImage);
		end;
	end;
end;