user2520938
user2520938

Reputation: 421

Getting the dimensions of a rendered text in Cimg library

I have an image of a rectangle, and I need to draw the rectangle's dimensions in it. Now I want to find out the size of a text I'm about to draw so that I can determine an appropriate font size, as to make sure the text does not go outside of the rectangles boundaries, but also not unnecessarily small. I was using this: http://www.codeproject.com/Articles/363908/Simple-two-file-graphics-library-for-C-Cplusplus library before but it as a bit to restricted in it's use, but it did have a function

int ezd_text_size( HEZDFONT x_hFont, const char *x_pText, int x_nTextLen, int *pw, int *ph )

Which given a font and a char* will calculate the length and width of the area the drawn text would require. I cannot find anything similar in the Cimg documentation though.

So does someone have experience with this issue using Cimg?

Upvotes: 2

Views: 1900

Answers (1)

bvalabas
bvalabas

Reputation: 301

I assume you want to use method CImg<T>::draw_text() to draw your text on a CImg<T> image. In that case, you have the possibility to call draw_text()on an empty instance, it will automatically set the image size to the minimal bounding box containing your text. Thus, the width() and height() of the resulting image gives you what you are looking for.

CImg<unsigned char> imgtext;
unsigned char color = 1;
imgtext.draw_text(0,0,"Hello guys !",&color,0,1,23);  // Draw with font height 23.
// Now, imgtext.width() and imgtext.height() gives you the dimensions you want.

It's easy then to check if the text fits your box size, and eventually reduce the font size until it does.

Upvotes: 4

Related Questions