Scaling ttf-font in Monkey2

In Monkey2 programming language it is possible to load ttf (and otf & fon) font directly and use the DrawText method of canvas to draw the text. But how to scale the font? In this example I made today it is done in a clumsy way, but may give you some ideas…

The source code:

Namespace myapp

#Import "IMG_0648.JPG"
#Import "transparent.png"

#Import "<std>"
#Import "<mojo>"

Using std..
Using mojo..


Class MyWindow Extends Window
	
	Const RAD:Double = Pi / 180	' 1 degreen in radians
	
	Field gfxBG:Image
	Field gfxTransparent:Image	' Just an transparent image where the text is drawn
	Field fontCanvas:Canvas		' Canvas for transparent image
	Field scaleVar:Float
	Field scale:Float			' Text scale (scales the "gfxTransparent")

	Method New( title:String="Scaling font in Monkey2",width:Int=800,height:Int=600,flags:WindowFlags=Null )
		Super.New( title,width,height,flags )
		
		gfxBG = Image.Load("asset::IMG_0648.JPG")

		' Load a 100 x 48 transparent image
		gfxTransparent = Image.Load("asset::transparent.png")		
		gfxTransparent.Handle = New Vec2f(0, 0)

		' Make a canvas from the transparent image to render the text to...
		fontCanvas = New Canvas(gfxTransparent)
		fontCanvas.Font = Font.Load("asset::SpeedballNo2NF.ttf", 21)
		fontCanvas.Color = Color.Yellow
		fontCanvas.DrawText("Sample Text",(100 - fontCanvas.Font.TextWidth("Sample Text")) / 2, 1)
		fontCanvas.Flush()		

		scale = 1
		scaleVar = 0
	End

	Method OnRender(canvas:Canvas) Override
	
		App.RequestRender()

		canvas.DrawImage(gfxBG, 0, 0)
		
		scaleVar = scaleVar + RAD * 2
		scale = 4 - Sin(scaleVar) * 1.5	' This the scale (if scale = 1, no scaling)
				
		' The text is scaled and centered
		canvas.DrawImage(gfxTransparent, (800 - 100.0 * scale) / 2, (600 - 48.0 * scale) / 2, 0, scale, scale)

		canvas.Flush()
		
	End

End

Function Main()
	New AppInstance
	New MyWindow
	App.Run()
End

Below is the video related to this post:

Feel free to use my code!

%d bloggers like this: