This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
xgaarocha's profile picture

[OpenPeripheral 1.1.1] Get "glasses_text" width

Started by xgaarocha, 06 June 2015 - 10:59 PM
xgaarocha #1
Posted 07 June 2015 - 12:59 AM
I've been trying to find a way to get the width (in pixels, not characters) for glasses_text objects but I can't find out how.
I've generated and looked trough the doc, searched on Google and still didn't find anything.

I know there was a function (now deprecated): glass.getStringWidth(str) but I also read that It didn't work correctly, as it assumed the font was monospace when it wasn't.

I want to know if there is any function that is hidden from the docs that can get me the width? The only solution I can think of is to manually find the width of every character, taking into account the scale property and adding up the width of every character.

Thanks for you attention.
flaghacker #2
Posted 07 June 2015 - 07:40 AM
I searched for this too, but I couldn't find anything aswell.

The problem is that multiple people can be linked to the same bridge, each with their own screen size so a getScreenSize method wouldn't make that much sense.
Bomb Bloke #3
Posted 07 June 2015 - 07:54 AM
Sounds like he doesn't care about the screen size, but rather the amount of pixels that a given string will take up. Which should be the same for all users, assuming the "scale" is the same for all of them.

I've not tried the glasses myself, but if there were a working version of glass.getStringWidth(str) available, I don't think it would be hidden away behind a broken one.
xgaarocha #4
Posted 16 June 2015 - 07:30 PM
Sorry for not answering quicker, I had some family problems.

Anyhow, I've worked out that characters are 5 pixels wide, times the scale. The only character I've found to be less than 5 pixels is the exclamation mark, which is 2 pixels wide.
Anyhow, here's the code i've come up with: (CHAR_HEIGHT is just there so I don't forget the value :P/>)

function GetTextWidth(textObject)
local CHAR_WIDTH = 5
local CHAR_HEIGHT = 8
local EXCLAMATION_WIDTH = 2
local text = textObject.getText()
local scale = textObject.getScale()
local width = 0

for i = 1, #str do
    if text:sub(i,i) == "!" then
       width = width + CHAR_WIDTH * scale  
    end
end

return width
end
Edited on 16 June 2015 - 05:31 PM
Deadlock989 #5
Posted 17 August 2015 - 10:37 PM
Here's how I do it:


function aligntexts(halign,texttable)
  for i,v in pairs(texttable) do
    v.setObjectAnchor(halign,"top")
  end
end

texttable is an array of glass.text objects

halign is either "left", "middle" or "right" (no point in passing it left, new text objects are already left-aligned)