Example of Own Font Class in Monkey X part 2

I decided to implement in an alternative way own font class to Monkey X to use with fonts converted with my Font 2 PNG, just to for passing time.

Check the previous post or the homepage of Font 2 PNG for format of the dat-file.

Screenshot of the program:

All you really have to understand is the simple format of the dat-file of a font to understand the source code below — and of course basic understanding of Monkey X.

Import mojo
Import brl.databuffer

Function Main()
	New MyApp
End

Class MyFont
	Field maxHeight:Int
	Field fontDat:DataBuffer
	Field gfxFont:Image
	Field scale:Float
End

Class MyApp Extends App
	
	Field gfxBG:Image
	Global font1:MyFont
	Global font2:MyFont

	Method OnCreate()
		
		' -------
		' Font 1
		' -------
		font1 = New MyFont
		font1.gfxFont = LoadImage("font1.png")
		font1.fontDat = New DataBuffer(95*4*2) ' 95 characters, for each character two 4 byte integers
		font1.scale = 1
		font1.maxHeight = 71
		font1.fontDat = DataBuffer.Load("monkey://data/font1.dat")

		' -------	
		' Font 2
		'--------
		font2 = New MyFont
		font2.gfxFont = LoadImage("font2.png")
		font2.fontDat = New DataBuffer(95*4*2) ' 95 characters, for each character two 4 byte integers
		font2.scale = 1.8
		font2.maxHeight = 43
		font2.fontDat = DataBuffer.Load("monkey://data/font2.dat")
		
		gfxBG = LoadImage("bg.jpg")
		
		SetDeviceWindow(640,480,0)
		
		SetUpdateRate(30)
	End
	
	Method OnRender()
		SetBlend AlphaBlend
		SetAlpha 1
		DrawImage gfxBG,0,0

		drawString(font1, "Testing font 1", 10, 10)
		drawString(font2, "Testing font 2", (640 - stringWidth(font2, "Testing font 2") * font2.scale) / 2, (480 - (font2.maxHeight * font2.scale)) / 2)
	End
	
	Function drawString(font:MyFont, text:String, x:Float, y:Float)
		Local len = text.Length()
		
		Local chrs:Int[]
		chrs = text.ToChars()
		
		For Local i = 0 To len - 1
			'                                 pos. in font.png                          width in pixels in font.png
			DrawImageRect font.gfxFont, x, y, font.fontDat.PeekInt((chrs[i]-32)*4*2), 0, font.fontDat.PeekInt((chrs[i]-32)*4*2 + 4), font.maxHeight,0,font.scale, font.scale,0
			x = x + font.fontDat.PeekInt((chrs[i]-32)*4*2 + 4) * font.scale
		Next

	End
	
	Function stringWidth:Int(font:MyFont,text:String)
		Local len:Int = text.Length()
		Local chrs:Int[]
		Local length:Int = 0
		
		chrs = text.ToChars()
		
		For Local i:Int = 0 To len - 1
			length = length + font.fontDat.PeekInt((chrs[i]-32)*4*2 + 4)
		Next
		
		Return length
	End

End Class

Feel free to use the code above.

 

%d bloggers like this: