Search code examples
gdicjk

gdi, get width of asian characters


        int dx[8];
        int fit;
        SIZE the_size;

        res = GetTextExtentExPointW(dc, L"WWWWWWWW", 8, -1, &fit, &dx[0], &the_size);

This works, dx is filled with numbers 7 14 21 etc. But when I try to do the same for asian characters, like L"薔薇薔薇薔薇薔薇", this function fails. I even created a font for this, it doesn't change anything.

        HFONT hFont = CreateFont(14,
            0,
            0,
            0,
            FW_DONTCARE,
            FALSE, //fdwItalic
            FALSE, //fdwUnderline
            FALSE, //fdwStrikeOut
            SHIFTJIS_CHARSET,
            OUT_DEFAULT_PRECIS,
            CLIP_DEFAULT_PRECIS,
            NONANTIALIASED_QUALITY, 
            VARIABLE_PITCH,
            TEXT("MS PGothic"));

        if (hFont == NULL) FUCK();

        SelectObject(dc, hFont);

Solution

  • The forth parameter should be the maximum width allowed, not -1. Use a large value instead. Check to make sure GetTextExtentExPointW succeeded.

    if(GetTextExtentExPointW(dc, L"薔薇薔薇薔薇薔薇", 8, 1000, &fit, &dx[0], &the_size))
    {
        ...
    }
    

    Note that a Unicode code point may require 4 bytes, or 2 wchar_t for each code point.