Calculate font scale to fit text in the box

asked 2013-02-22 18:46:45 -0500

Darker gravatar image

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.

edit retag flag offensive close merge delete


afaik, HERSHEY is a proportional font, not all letters have same width. maybe you need a lookup-table (width per letter)

berak gravatar imageberak ( 2013-02-23 05:33:04 -0500 )edit

But I'm only trying to fit height. Width must be fit by user - correct button width must be defined, or the font overflows.

Darker gravatar imageDarker ( 2013-02-23 06:49:12 -0500 )edit