Using Transforms
Introduction
We show in our tutorial on Oxygene for Java how you can move, translate and/or scale a shape by transforming the canvas before drawing the shape. You save the canvas before the transformation and restore it after use. Our demonstration code was easy to adapt for use in Smart Mobile Studio. The following code, based on our Graphics2D Path Applet, demonstrates translation and scale. See the demo beneath the code. For an example of rotation see Getting Started with Smart Canvas Game Projects. George Wright makes good use of rotation and translation in the drawing unit of RandomPlatformScroller. The converted student program MyFirstJS creates ellipses by scaling the canvas of a circle.
The Code
You can compile this code with Versions 2.2 and 3.0 of Smart Mobile Studio.
unit Unit1; interface uses System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application, SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics; type TCanvasProject = class(TW3CustomGameApplication) private FCounter: integer; protected procedure ApplicationStarting; override; procedure ApplicationClosing; override; procedure PaintView(Canvas: TW3Canvas); override; end; implementation procedure TCanvasProject.ApplicationStarting; begin inherited; GameView.Delay := 40; GameView.StartSession(True); end; procedure TCanvasProject.ApplicationClosing; begin GameView.EndSession; inherited; end; procedure TCanvasProject.PaintView(Canvas: TW3Canvas); procedure stickmanPath; begin Canvas.moveToF(50.0, 50.0); //Top of head Canvas.QuadraticCurveToF(60.0, 55.0, 50.0, 60.0); //Bottom of head Canvas.lineToF(50.0, 80.0); //Pelvis Canvas.lineToF(55.0, 110.0); //Right foot Canvas.moveToF(50.0, 50.0); //Back to top of head Canvas.QuadraticCurveToF(40.0, 55.0, 50.0, 60.0); //Bottom of head Canvas.moveToF(50.0, 80.0); //Pelvis Canvas.lineToF(45.0, 110.0); //Left foot Canvas.moveToF(50.0, 63.0); //Shoulder Canvas.lineToF(58.0, 85.0); //Right hand Canvas.moveToF(50.0, 63.0); //Shoulder Canvas.lineToF(40.0, 85.0); //Left hand end; begin inc(FCounter); // Clear background Canvas.FillStyle := 'white'; Canvas.FillRectF(0, 0, GameView.Width, GameView.Height); //Draw red translated stickman Canvas.StrokeStyle := 'red'; Canvas.Save; Canvas.Translate(100, 0); Canvas.BeginPath; stickmanPath; Canvas.Stroke; Canvas.ClosePath; Canvas.Restore; //Draw blue translated and scaled stickman Canvas.StrokeStyle := 'blue'; Canvas.Save; Canvas.Translate(FCounter, FCounter); Canvas.Scale(1.0 + 0.005 * FCounter, 1.0 + 0.005 * FCounter); Canvas.BeginPath; stickmanPath; Canvas.Stroke; Canvas.ClosePath; Canvas.Restore; if FCounter = 100 then FCounter := 0; end; end.
The Demo
If TransformDemo does not run in your current browser, please try another (such as Chrome). If you see no display at school, the security system might have blocked it. You can try instead this direct link to the program running on its own page.