How to know the bounds of a single character?

Magick++ is an object-oriented C++ interface to ImageMagick. Use this forum to discuss, make suggestions about, or report bugs concerning Magick++.
Post Reply
flying_camel
Posts: 2
Joined: 2015-06-19T08:59:54-07:00
Authentication code: 6789

How to know the bounds of a single character?

Post 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!
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

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

Post by fmw42 »

flying_camel
Posts: 2
Joined: 2015-06-19T08:59:54-07:00
Authentication code: 6789

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

Post 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.
Post Reply