1
votes

The following code draws text using DrawText (single line) and DrawTextEx (wrapping). I want both v-centered.

    CRect rect1(50, 50, 100, 125);
    CRect rect2(100, 50, 500, 125);

    CPen pen(PS_SOLID, 0, RGB(192, 192, 192));

    pDC->MoveTo(rect1.left, rect1.top);
    pDC->LineTo(rect2.right, rect2.top);
    pDC->MoveTo(rect1.left, rect1.bottom);
    pDC->LineTo(rect2.right, rect2.bottom);

    pDC->DrawText("hello", rect1, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
    pDC->DrawTextEx("0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 ",
                    rect2, DT_EDITCONTROL | DT_WORDBREAK | DT_LEFT | DT_VCENTER, NULL);

The output is figure below, looks like single line is v-centered but not the one with wrapping. Also, note that some of the upper line is covered, which should be addressed as well.

enter image description here

1
Documentation for DT_VCENTER states: "Centers text vertically. This value is used only with the DT_SINGLELINE value." - Adrian Mole

1 Answers

4
votes

DT_VCENTER can only be used in combination with DT_SINGLELINE. For multi-line drawing, use DT_CALCRECT to obtain the height, then manually calculate the center. Example:

CString str = "0123456789 0123456789 0123456789 0123456789 0123456789";
CRect rc = rect2;
dc.DrawText(str, &rc, DT_EDITCONTROL | DT_WORDBREAK | DT_LEFT | DT_CALCRECT);
rc.OffsetRect(0, (rect2.Height() - rc.Height()) / 2);
dc.DrawText(str, &rc, DT_EDITCONTROL | DT_WORDBREAK | DT_LEFT);