locked
Direct2D DrawText, position text's upper left-hand corner

    Question

  • I am displaying text in a metro application with Direct2D using a SurfaceImageSource in order to interop with C#.

    When calling the DrawText method, I would like to position the upper left-hand corner of the displayed text to the upper left-hand corner of the layoutRect. Based on the documentation, setting TextAlignment to DWRITE_TEXT_ALIGNMENT_LEADING, and setting ParagraphAligment to DWRITE_PARAGRAPH_ALIGNMENT_NEAR should achieve exactly that (the leading edge is aligned to the leading edge of the layout box, and the upper edge is aligned to the upper edge of the box).

    However, the displayed text does not get aligned like that. The middle line of the text gets aligned to the top of the layout box, and interestingly, the trailing edge of the first character gets aligned to the leading edge of the layot box (so if I draw one character to a layoutRect of which the left field is set to zero, then nothing gets displayed on the screen (if I draw more than one character, then the second character is the first which is displayed)).

    What am I doing wrong? Is this a bug? I haven't tried it yet with a native render target.

    Friday, March 23, 2012 10:26 AM

Answers

  • Hi Mark,

    As a first step - are you taking into account the offset that is returned when you call BeginDraw() on the SurfaceImageSource?  This offset will usually be nonzero, so if you don't account for it then any content you draw will likely be offset to the top and left, which could explain why your first character is getting clipped.

    One easy way to accomplish this is by calling ID2D1DeviceContext::SetTransform() with a transform matrix based on the offset returned by BeginDraw.

    • Marked as answer by MarkVincze Friday, March 23, 2012 9:44 PM
    Friday, March 23, 2012 5:41 PM

All replies

  • Hi Mark,

    As a first step - are you taking into account the offset that is returned when you call BeginDraw() on the SurfaceImageSource?  This offset will usually be nonzero, so if you don't account for it then any content you draw will likely be offset to the top and left, which could explain why your first character is getting clipped.

    One easy way to accomplish this is by calling ID2D1DeviceContext::SetTransform() with a transform matrix based on the offset returned by BeginDraw.

    • Marked as answer by MarkVincze Friday, March 23, 2012 9:44 PM
    Friday, March 23, 2012 5:41 PM
  • That was exactly the problem, thanks for the help.

    If anyone is interested, the solution was to do this after BeginDraw:

    POINT offset = {0, 0};
    
    surfaceImageSourceNative->BeginDraw(updateRect, &surface, &offset)
    
    d2dDeviceContext->SetTransform(D2D1::Matrix3x2F::Translation(offset.x, offset.y));


    Friday, March 23, 2012 9:44 PM