如题:
因为字体的宽度是不一样的,现在有一种字体,
//创建字体
     VERIFY(mFont.CreateFont(120,0,0,0,
                   FW_NORMAL,
FALSE,FALSE,
0,
GB2312_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY,
DEFAULT_PITCH | FF_SWISS,
_T("方正准圆简体"))); 
有一个CString str;
比如:str为"999"和str为"中央电视台"是在显示出来的宽度是不一样,现在问题就是:怎么获取字符串str的宽度?GetTextMetrics()函数获取可不可以?
给个例子谢谢!!

解决方案 »

  1.   

    用 DrawText 或 DrawTextEx 可以计算出来
      

  2.   

    当然是用GetTextMetrics了 它的第一个参数是传递DC嘛,你的DC要Select某种font。
      

  3.   

    关于精确计算字符串写屏宽度==GDI深入讨论==
      

  4.   


    int DrawTextEx(
      HDC hdc,                     // handle to DC
      LPTSTR lpchText,             // text to draw
      int cchText,                 // length of text to draw
      LPRECT lprc,                 // rectangle coordinates
      UINT dwDTFormat,             // formatting options
      LPDRAWTEXTPARAMS lpDTParams  // more formatting options
    );
    dwDTFormat 填 DT_CALCRECTDT_CALCRECT Determines the width and height of the rectangle. If there are multiple lines of text, DrawTextEx uses the width of the rectangle pointed to by the lprc parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawTextEx modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawTextEx returns the height of the formatted text, but does not draw the text. 
      

  5.   

    用GetTextMetrics()计算出来的不正确啊
      

  6.   

    pDC-> SelectObject(&mFont);
    使用CSize cs=pDC-> GetTextExtent(str);
    或者CSize cs = pDC->GetTextExtent(str); 获取的字符串宽度怎么就才获取一个字的宽度呢?
      

  7.   

    GetTextExtentExPoint();
    记得好像是这个函数。
      

  8.   

    GetTextMetrics()好像有误差!
      

  9.   


    不会用这个函数,能否给个例子,比如就计算字符串CString str = _T"中央电视台"的长度?
    字体为VERIFY(mFont.CreateFont(120,0,0,0,
      FW_NORMAL,
    FALSE,FALSE,
    0,
    GB2312_CHARSET,
    OUT_DEFAULT_PRECIS,
    CLIP_DEFAULT_PRECIS,
    DEFAULT_QUALITY,
    DEFAULT_PITCH | FF_SWISS,
    _T("方正准圆简体")));  
      

  10.   

    CString str;
    int dis_num = 0,line_width = 0;
    SIZE str_size = {0};
    GetTextExtentExPoint(hDC,str,lstrlen(str),line_width,&dis_num,NULL,&str_size);
    str = "导视"时得到str_size{cx=30,cy=16}
    str = "中央一台"时得到str_size{cx=60,cy=16}
    字体为VERIFY(mFont.CreateFont(50,0,0,0,
    FW_NORMAL,
    FALSE,FALSE,
    0,
    GB2312_CHARSET,
    OUT_DEFAULT_PRECIS,
    CLIP_DEFAULT_PRECIS,
    DEFAULT_QUALITY,
    DEFAULT_PITCH | FF_SWISS,
    _T("方正准圆简体")));我动态移动窗口来显示只有一半能显示出来啊
    int cx=GetSystemMetrics(SM_CXSCREEN);   //屏幕宽度
    int cy=GetSystemMetrics(SM_CYSCREEN);   //屏幕高度
    this->MoveWindow(cx-str_size.cx,100,cx,200,true);//移动窗体并改变大小求帮忙