Calculate the display width of a string?

Well, I have a problem with right aligned text.

In a window I drew a text that is a variable: can be long, can be short... Depends of the value inside this varibale.

As rect size, I was using "rect.width", because this is the only way to make the align 'right' param works, and I really need this text to be right aligned.

The problem now is that I need to put an icon behind this text, but I don't know how to find the exact width of the text to draw this icon behind it, and not below or above it.

I want:
text

 

What I don't want:

                                text

 

[text -> This is my fail to represent that text is above the

 

I need it, please. Or a way to draw an icon inside a "drawText". And if you will say that I might use drawTextEx, teach me how to use this thing, because this do not works for me. The escape codes do not appear and I don't know how to align it to right too.

Tks people.
Well, to get the width of text, the Bitmap class has a function, measureTextWidth, that will do that for you. However, you could just add the icon's width to the text's X position, and draw it left aligned from the icon and on.
UPDATE

Forget my question, I figuret it out. Thank you very much!
 

To anyone that would like to know how to do this: 

var width (or whatever you want to call it) = this.contents.measureTextWidth(MyTextVariable or 'String');Must be inside a Window_Base superclass or subsclass function. 

=============

 OLD

Yeah, I did it for the left aligned ones, but for the right aligned or I draw the icon on the end of the text (what looks really awfull) or I find a way to measure the text width. With this width all I need to to is:

vax x = Graphics.boxwidth - My_Variable_with_the_line_width - any_correction_value;

And I really need this text to be right aligned. ):

Anyway, how do I use this measure text function of the Bitmap class?

I thought I might just do this:


var x = Bitmap.measureTextWidth(MyTextVariable or 'String');

But it's throwing me an error in the console: "cannot read property "save" of undefined"

what does this means?


Code:
* Returns the width of the specified text.** @method measureTextWidth* @param {String} text The text to be measured* @return {Number} The width of the text in pixels*/Bitmap.prototype.measureTextWidth = function(text) {var context = this._context;context.save();context.font = this._makeFontNameText();var width = context.measureText(text).width;context.restore();return width;};

Original thread: https://forums.rpgmakerweb.com/threads/calculate-the-display-width-of-a-string.52233/