The following is a class that allows you to draw game tile graphics easily. A game tile is basically just a small chunk of graphics (typically 16×16 or 32×32 pixels in size) that you use to display game maps. Typical examples are the older Super Mario games from Nintendo, or the Sega megadrive Sonic games.
Here is an example of a tile-set which you can use (the tileset below is public domain)
And here is the class you can use to draw the tiles
[sourcecode language=”delphi”]
unit SpriteSheet;
interface
uses w3ctrls, w3graphics, w3System;
type
TW3SpriteSheet = Class(TObject)
private
FImage: TW3Image;
FReady: Boolean;
FColumns: Integer;
FRows: Integer;
FTotal: Integer;
FWidth: Integer;
FHeight: Integer;
procedure HandleImageReady(sender:TObject);
Procedure setWidth(aValue:Integer);
procedure setheight(aValue:Integer);
Procedure ReCalcInfo;
public
Constructor Create;virtual;
destructor Destroy;Override;
Procedure LoadImage(aUrl:String);
Procedure Draw(Canvas:TW3Canvas;dx,dy:Integer;FrameIndex:Integer);
Property SpriteWidth:Integer read FWidth write setWidth;
Property SpriteHeight:Integer read FHeight write setHeight;
Property Ready:Boolean read FReady;
End;
implementation
Constructor TW3SpriteSheet.Create;
Begin
inherited Create;
FImage:=TW3Image.Create(NIL);
FImage.OnLoad:=HandleImageReady;
FWidth:=32;
FHeight:=32;
end;
destructor TW3SpriteSheet.Destroy;
Begin
FImage.onLoad:=NIL;
FImage.free;
inherited;
end;
Procedure TW3SpriteSheet.setWidth(aValue:Integer);
Begin
FWidth:=Max(aValue,4);
ReCalcInfo;
end;
procedure TW3SpriteSheet.setheight(aValue:Integer);
Begin
FHeight:=Max(aValue,4);
ReCalcInfo;
end;
Procedure TW3SpriteSheet.ReCalcInfo;
var
img : Variant;
Begin
if FReady then Begin
img:=ObjToVariant(FImage.TagRef);
FColumns:=(img.width+1) div FWidth;
FRows:=(img.height+1) div FHeight;
FTotal:=FColumns * FRows;
end else Begin
FColumns:=0;
FRows:=0;
FTotal:=0;
end;
end;
procedure TW3SpriteSheet.HandleImageReady(sender:TObject);
Begin
FReady:=True;
ReCalcInfo;
end;
Procedure TW3SpriteSheet.LoadImage(aUrl:String);
Begin
FReady:=False;
ReCalcInfo;
FImage.LoadFromUrl(aUrl);
end;
Procedure TW3SpriteSheet.Draw(Canvas:TW3Canvas;
dx,dy:Integer;FrameIndex:Integer);
var
sx,sy: Integer;
Begin
if FReady then
Begin
sx:=FrameIndex mod FColumns;
sy:=FrameIndex div FRows;
Canvas.DrawImageF(ObjToVariant(FImage.TagRef),
sx*SpriteWidth, sy*SpriteHeight,
SpriteWidth, SpriteHeight,
dx, dy, SpriteWidth, SpriteHeight);
end;
end;
[/sourcecode]
In our next installment I’ll give you some examples of how to use it