Page 1 of 1

How to know the bounds of a single character?

Posted: 2015-06-19T09:20:25-07:00
by flying_camel
Hello,
I am using a monoapaced font (DejaVu-Sans-Mono) to render some text on an image. I know the size of the image, its density, and its font point size. Since I am using a monospaced font, I assume that all the symbols reserve the same size. Is it possible to figure out this size?

Basically, I want to know the starting position of the nth character before even drawing it. And I think I can calculate this if I know the bounds of a single character.

Thanks in advance!

Re: How to know the bounds of a single character?

Posted: 2015-06-19T10:16:59-07:00
by fmw42

Re: How to know the bounds of a single character?

Posted: 2015-06-19T11:41:23-07:00
by flying_camel
Thanks for your answer.

Here is an example of how I get it now. Not sure if it is the best way, but it seems to work.

Code: Select all

#include <Magick++/Geometry.h>
#include <Magick++/Image.h>
#include <Magick++/Drawable.h>

using namespace Magick;

int main(int argc, char** argv)
{
    Image img(Geometry(600, 400), Color("white"));
    img.font("DejaVu-Sans-Mono");
    img.fontPointsize(70);

    char a_buf[512];
    sprintf(a_buf, "█");
    DrawableText text(100, 100, a_buf);
    img.draw(text);
    img.write("test.png");

    Magick::TypeMetric metric;
    img.fontTypeMetrics("", &metric);

    int char_width = metric.maxHorizontalAdvance();
    int char_height = img.fontPointsize();

    printf("Character width = %d\nCharacter height = %d", char_width, char_height);
    return 0;
}
Output
Character width = 42
Character height = 70
I used GIMP to measure the size of the printed character, and it matched the output.