Hi,
let’s say I want to draw two text labels at the far right of the screen. In some situations, they may overlap. To avoid this, I would like to draw the first label (‘text1’) at a given x-position, and then draw the second label (‘text2’) at x + the pixel width of ‘text1’.
How can I calculate the pixel length (width) of a text string so that I can use this value with the drawtext function (if this is possible)?
Hi,
There is currently no native function in ProBuilder to calculate the pixel width or length of a text string dynamically. The rendering metrics (how much space a font takes up on the screen) are not accessible via the code.
However, since you are drawing labels at the far right of the screen, the best way to prevent overlapping without knowing the exact text width is to use the ANCHOR instruction with XSHIFT and YSHIFT (which uses pixels instead of bar index/price).
// We only want to draw this on the last bar to act as a label
DEFPARAM DrawOnLastBarOnly = True
// Note1: When anchoring, positive X moves Right, Negative moves Left.
// Note2: When anchoring, positive Y moves Up, Negative moves Down.
// Since we cannot calc string width, we must define a fixed X/Y pixel offset.
// Vertical Stacking (example: We anchor to the Bottom Right)
offsetLabel1 = 170
offsetLabel2 = 150 // Text 2 is placed below 1
DRAWTEXT("Label 1 (Top)", -250, offsetLabel1) ANCHOR(bottomRIGHT, XSHIFT, YSHIFT)
DRAWTEXT("Label 2 (Below)", -250, offsetLabel2) ANCHOR(bottomRIGHT, XSHIFT, YSHIFT)
// Horizontal (example: We anchor to the Top Right)
offsetText1 = -350
offsetText2 = -150 // Text 2 is placed to the right of Text 1
DRAWTEXT("Text 1", offsetText1, -150) ANCHOR(TOPRIGHT, XSHIFT, YSHIFT)
DRAWTEXT("Text 2", offsetText2, -150) ANCHOR(TOPRIGHT, XSHIFT, YSHIFT)
RETURN