PDA

View Full Version : center text inside a rectangle



Vincent22
04-02-2012, 09:13 AM
Hi everybody.
I want to create simple buttons made up of a streched square and a label.
I have a "drawButton" class and I'd like to center the button's text label using buttons coordinates.
I found a good way to center text on X axis but I cannot center the text on the Y axis.

Here is my code:

drawing text function:


void Font(void *font, char *text, float x, float y)
{
glRasterPos2f(x, y);

while (*text != '\0')
{
glutBitmapCharacter(font, *text);
//std::cout << *text << std::endl;
++text;
}
}

drawButton class:


class drawButton
{
public:
drawButton(float w, float h, Vertex pos, Color c, char *text): width(w), height(h), position(pos), bColor(c), delay(0.1), depth(0.02), label(text) { m_vertexBuffer = m_indexBuffer = m_colorBuffer = 0; }
~drawButton();
bool initialize();
void render();
char *label;

float width, height, delay, depth;
Vertex position;
Color bColor;
private:

GLuint m_vertexBuffer, m_indexBuffer, m_colorBuffer, m_texture;

vector<Color> m_colors;
vector<GLuint> m_indices;
vector<Vertex> m_vertices;
vector<texCoords> m_texCoord;

void drawLabel();


};


void drawButton::drawLabel() {



float charDim = 0.025f;
int somma = 0;
for (int i = 0; i < strlen(label); ++i) {
++somma;
}

float xpos = somma/2 * charDim;
xpos+=charDim;
float center = position.x+(width/2);


Font(GLUT_BITMAP_TIMES_ROMAN_24,label,center-xpos,position.y);

}