GDI+字符串测量

发布时间 2023-12-04 17:29:04作者: 左边的翼

  关于GDI+对字符串的测量官方文档中给出5种重载函数,5种重载分为两类,两类的分类方式是按照字符串以何种方式输出定义。下面文字给出官方对两类定义的描述:

第一类:The Graphics::MeasureString method measures the extent of the string in the specified font,format, and layout rectangle.

第二类:The Graphics::MeasureString method measures the extent of the string in the specified font and layout rectangle.

  通过上述英文描述可看出,两类的区分是按输出格式定义。以下代码展示在字体大小不同的情况下的输出效果:

    WCHAR string[] = L"上善若水";
    Gdiplus::Font ft(L"KaiTi", 20/*50*//*70*/);
    RectF layoutRect(10.0f, 10.0f, 200.0f, 330.0f);
    StringFormat strF;
    strF.SetAlignment(StringAlignmentFar);
    RectF boundRect;
    graphics.DrawRectangle(&Pen(Color(255, 0, 0)), layoutRect);
    graphics.MeasureString(string, 4, &ft, layoutRect, &strF, &boundRect);
    graphics.DrawString(string, 4, &ft, boundRect, &strF, &SolidBrush(Color(0, 255, 0)));
    graphics.DrawRectangle(&Pen(Color(0, 0, 255)), boundRect);

字体大小为20\50\70效果如下:

 通过效果显示可看出,字符串测量仅限定在制定的区域中,当字体超出范围将不再显示。