Microsoft Small Basic

Program Listing: KTK906-0
' Measure Text Width in Pixels 0.2
' Copyright (c) 2014 Nonki Takahashi. All rights reserved.
'
' History:
' 2014-02-17 Adopted for Silverlight. (KTK906-0)
' 2014-02-13 Created. (KTK906)
'
GraphicsWindow.Title = "Measure Text Width in Pixels 0.2"
Not = "False=True;True=False"
Init()
Main()
Sub Init
gw = 598
gh = 428
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
GraphicsWindow.BrushColor = "LightGray"
GraphicsWindow.FillRectangle(0, 0, gw, 100)
GraphicsWindow.BrushColor = "Black"
GraphicsWindow.DrawText(10, 10, "Text")
txt = Controls.AddTextBox(50, 10)
Controls.SetTextBoxText(txt, "test")
GraphicsWindow.DrawText(10, 40, "Size")
size = Controls.AddTextBox(50, 40)
Controls.SetTextBoxText(size, GraphicsWindow.FontSize)
GraphicsWindow.DrawText(260, 10, "Font")
font = Controls.AddTextBox(300, 10)
Controls.SetTextBoxText(font, GraphicsWindow.FontName)
GraphicsWindow.DrawText(260, 40, "Width")
width = Controls.AddTextBox(300, 40)
Controls.SetTextBoxText(width, 0)
btn = Controls.AddButton("Measure", 10, 70)
clicked = "False"
Controls.ButtonClicked = OnButtonClicked
EndSub
Sub OnButtonClicked
clicked = "True"
EndSub
Sub Main
While "True"
If clicked Then
GraphicsWindow.BrushColor = "White"
GraphicsWindow.FillRectangle(0, 100, gw, gh - 100)
GraphicsWindow.FontName = Controls.GetTextBoxText(font)
fs = Controls.GetTextBoxText(size)
GraphicsWindow.FontSize = fs
GraphicsWindow.BrushColor = "Black"
GraphicsWindow.DrawText(0, 100, "||")
y0 = 100
y1 = 100 + fs
x0 = 0
x1 = fs * 2
If gw < x1 Then
x1 = gw - 1
EndIf
Measure()
GraphicsWindow.BrushColor = "White"
GraphicsWindow.FillRectangle(0, 100, gw, gh - 100)
GraphicsWindow.BrushColor = "Gray"
GraphicsWindow.FillRectangle(0, 100 + fs, gw, 1)
px0 = px
str = "|" + Controls.GetTextBoxText(txt) + "|"
GraphicsWindow.BrushColor = "Black"
GraphicsWindow.DrawText(0, 100, str)
x1 = fs * Text.GetLength(str)
If gw < x1 Then
x1 = gw - 1
EndIf
Measure()
Controls.SetTextBoxText(width, (px - px0))
clicked = "False"
Else
Program.Delay(100)
EndIf
EndWhile
EndSub
Sub Measure
y = Math.Floor((y0 + y1) / 2)
For x = x0 To x1
color = GraphicsWindow.GetPixel(x, y)
If Not[Text.EndsWith(color, "FFFFFF")] Then
left = x
x = x1 ' break
EndIf
EndFor
For x = x1 To x0 Step -1
color = GraphicsWindow.GetPixel(x, y)
If Not[Text.EndsWith(color, "FFFFFF")] Then
right = x
x = x0 ' break
EndIf
EndFor
For x = right To x0 Step -1
color = GraphicsWindow.GetPixel(x, y)
If Text.EndsWith(color, "FFFFFF") Then
right = x + 1
x = x0 ' break
EndIf
EndFor
px = right - left
EndSub