Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Calculate font scale to fit text in the box

I have a button created in openCV and I need to fit a text in it. How do I compute the font scale if I want to fit it by width and I know the width of the box?

int font = CV_FONT_HERSHEY_COMPLEX_SMALL;  //defining font
double scale = ((float)(height-3))/20.0;   //So far, I just try to divide height by 20
Size textSize = getTextSize(value, font, scale, 1, &bottom);  //Geting text rect
Point textOrg((width - textSize.width)/2+x, (height + textSize.height)/2+y); //Computing point to center the text in the button
putText(*screen, value, textOrg, font, scale, Scalar(0,0,255), 1);//Printing txt in RED color

Now, I do simple height division, which works, but doesn't really make text fit - and in extreme cases (too small, to large box) the text either overflows or does not use desired 95% of boxes height.