DirectWrite align text center

2.1k views Asked by At

I am trying to align center the text I have to draw. I use ID2D1RenderTarget::DrawTextLayout method. The problemn is that if I set the text horizontal alignment to DWRITE_TEXT_ALIGNMENT_LEADING (the default value) the text is drawn proberly, but if I change this value to DWRITE_TEXT_ALIGNMENT_CENTER the text is shifted right.

The example string is

Internal Amazing 
Scupper

Following are the outcomes (the first is alignment leading):

enter image description here enter image description here

2

There are 2 answers

1
Gnietschow On BEST ANSWER

My comment as an answer (yeah, guessed right :)):

Just a quick guess: Did you check that the maxwidth your layout box isn't too broad, so the center would end there at the right?

The IDWriteTextLayout used by ID2D1RenderTarget::DrawTextLayout method defines a maximum width of the layout box, which determines where the text is centered. It can be manipulated by the methods of the interface (GetMaxWidth and SetMaxWidth).

0
Sempai-Dami1 On

When you create the text layout, you cannot change the width and height to something greater afterwards. You should use max screen coords when creating the layout then change the max width and height to the desired size. You should use render_tgt->DrawText(...) method for this example or release and recreate the layout interface every time the text, font name, and a lot of other various things like typography are changed. I created an array of layout and typography events that can be reapplied to the layout interface every time it is recreated. You do not need to recreate the layout for font size, since you can resize the text or individual characters with the layout interface

// Set the layout to maximum screen size
FLOAT maxX = (FLOAT)GetSystemMetrics(SM_CXFULLSCREEN); // * XD2D::pix_to_dips.x;
FLOAT maxY = (FLOAT)GetSystemMetrics(SM_CYFULLSCREEN); // * XD2D::pix_to_dips.y;

XS_DWRITE_DEV_FACTORY->CreateTextLayout
(
    dstring,
    dlength,
    (*pp_txt_format),
    maxX,
    maxY,
    pp_txt_layout
);

// Resize to the requested size or minimum allowed size
(*pp_txt_layout)->SetMaxWidth(max(req_xsize, (*pp_txt_layout)->GetFontSize()));
(*pp_txt_layout)->SetMaxHeight(max(req_ysize, (*pp_txt_layout)->GetFontSize()));