Char position in ofTrueTypeFont

Hello !

I’m looking for a solution to find the x/y position (in pixel) of any character in a string draw by ofTrueTypefont.

Any cue ?

Thank’s

hi you can call ofTrueTypeFont’s const ofMesh & getStringMesh(const std::string & s, float x, float y, bool vflip=true) const;

So,

//ofTrueTypeFont font; asuming it is properly loaded and set.

const auto& mesh = font.getStringMesh(textToDraw, posXToDrawString, posYToDrawString);

const auto& vertices = mesh.getVertices();

so from the vertices of the mesh you can extract the position of each char. Every 4 vertices define the rectangle of a specific char.


size_t charIndex = 2; // just the char index you want to get its position.

if((charIndex * 4 + 3) < vertices.size()){// just make sure you are not falling out of bounds
size_t vertIndex = charIndex * 4;
vertices[vertIndex] //top left vertex
vertices[vertIndex + 1] //top right vertex
vertices[vertIndex + 2] //bottom right vertex
vertices[vertIndex + 3] //bottom left vertex 

//you can also make an ofRectangle from which you can get useful info really easily.  if you dont know ofRectangle class you must give it a look. it is super useful.

auto r = ofRectangle(vertices[vertIndex] , vertices[vertIndex + 2] );//this constructor takes the top left and bottom right points to define the rectangle.

//then you can do 
r.getCenter()

if(r.inside(ofGetMouseX(), ofGetMouseY() ) ){
// will be true if the mouse is over the character
}

}

Thank you Roy !

in case it’s helpful, another way I’ve done this in the past is to get the string as shapes and go through the array of paths (which correspond to letters) and find the bounding box of each one (you have to go through the outlines / polylines of the path). It’s slightly more complicated than the approach Roy suggested…