summaryrefslogtreecommitdiff
path: root/bitmapfont.mod/bitmapfont.bmx
blob: 67bcd1fdc945d0abe9ba14beed7c38f7e0f7ea30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
Module noddybox.bitmapfont

ModuleInfo "Framework: Simple Bitmap Font Routines"
ModuleInfo "Copyright: Public Domain"
ModuleInfo "Author: Ian Cowburn"
ModuleInfo "Version: $Revision$"

' $Id$

Import brl.Max2D
Import brl.Basic


Strict

Type BitmapFont

	Const NOCHR=95
	
	Field img:TImage[NOCHR]
	Field height:Int[NOCHR]
	Field width:Int[NOCHR]
	Field is_fixed:Int

	Function Load:BitmapFont(path:String, image_flags:Int)
		Local fnt:BitmapFont
		Local str:TStream
		Local magic:String
		Local f,x,y
		
		str=ReadStream(path)

		If (Not str) Then Return Null
		
		fnt=New BitmapFont
		
		magic=ReadString(str,4)
		
		If (magic<>"BMF1")
			CloseStream(str)
			Return Null
		EndIf
		
		fnt.is_fixed=Readint(str)
		
		For f=0 Until NOCHR
			fnt.width[f]=Readint(str)
			fnt.height[f]=Readint(str)

			fnt.img[f]=CreateImage(fnt.width[f],fnt.height[f],1,image_flags)

			Local pm:TPixmap=LockImage(fnt.img[f])

			For x=0 Until fnt.width[f]
				For y=0 Until fnt.height[f]
					WritePixel(pm,x,y,Readint(str))
				Next
			Next
			
			UnlockImage(fnt.img[f])
		Next
		
		CloseStream(str)

		Return fnt
	End Function
	
	Method DrawColoured(txt:String, x:Int, y:Int, red:Int, green:Int, blue:Int)
		Local f,r,g,b,c
		Local xs#,ys#
		
		GetScale(xs,ys)
		
		GetColor(r,g,b)
		SetColor(red,green,blue)
		
		For f=0 Until Len(txt)
			c=txt[f]-32
			DrawImage(img[c],x,y)
			x:+width[c]*xs
		Next
		
		SetColor(r,g,b)
	End Method
	
	Method Draw(txt:String, x:Int, y:Int)
		DrawColoured(txt,x,y,255,255,255)
	End Method

	Method CentreColoured(txt:String, y:Int, red:Int, green:Int, blue:Int)
		If is_fixed
			DrawColoured(txt,GraphicsWidth()/2-Len(txt)*width[0]/2,y,red,green,blue)
		Else
			DrawColoured(txt,GraphicsWidth()/2-TextWidth(txt)/2,y,red,green,blue)
		EndIf
	End Method

	Method Centre(txt:String, y:Int)
		If is_fixed
			DrawColoured(txt,GraphicsWidth()/2-Len(txt)*width[0]/2,y,255,255,255)
		Else
			DrawColoured(txt,GraphicsWidth()/2-TextWidth(txt)/2,y,255,255,255)
		EndIf
	End Method

	Method TextWidth:Int(txt:String)
		Local w
		Local xs#,ys#
		
		GetScale(xs,ys)

		For Local f=0 Until Len(txt)
			w:+width[txt[f]-32]*xs
		Next
		Return w
	End Method

	Method TextHeight:Int(txt:String)
		Local h:Int=0
		Local xs#,ys#
		
		GetScale(xs,ys)

		For Local f=0 Until Len(txt)
			h=Max(h,height[txt[f]-32]*ys)
		Next

		Return h
	End Method

End Type