汉字笔画的计算。

来源:互联网 发布:淘宝消费总额查询 编辑:程序博客网 时间:2024/05/17 00:19
哈,新发现,通过提取楷体的字形轮廓可以获得汉字笔画。只不过选用的字体必须是楷体。其他字体不行。
这功能没什么用途吧,我只是好玩而已。

  1. int GetCharStrokes(UINT ch)
  2. {
  3.     HFONT hFont;
  4.     {   // create font;
  5.         LOGFONT lfFont;
  6.         memset(&lfFont, 0, sizeof(lfFont));
  7.         lstrcpy(lfFont.lfFaceName, "楷体_GB2312");
  8.         lfFont.lfHeight    = 72;
  9.         lfFont.lfWeight    = FW_NORMAL;
  10.         lfFont.lfItalic    = FALSE;
  11.         lfFont.lfStrikeOut = FALSE;
  12.         lfFont.lfCharSet = DEFAULT_CHARSET;
  13.         lfFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
  14.         lfFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  15.         lfFont.lfQuality =      DRAFT_QUALITY;
  16.         lfFont.lfPitchAndFamily = DEFAULT_PITCH;
  17.         hFont = CreateFontIndirect(&lfFont);
  18.     }
  19.     HDC hDC = GetDC(NULL);
  20.     if (hDC==NULL) return 0;
  21.     HGDIOBJ hOldFont = SelectObject(hDC,hFont);
  22.     MAT2 mat;
  23.     memset(&mat,0,sizeof(mat));
  24.     mat.eM11.value = 1;
  25.     mat.eM22.value = -1;
  26.     GLYPHMETRICS gm;
  27.     memset(&gm,0,sizeof(gm));
  28.     DWORD dwSize = GetGlyphOutline(hDC,ch,GGO_NATIVE,&gm,0,NULL,&mat);
  29.     int cnt = 0;
  30.     LPVOID pBuff = NULL;
  31.     if (dwSize>0)
  32.     {
  33.         pBuff = malloc(dwSize);
  34.         memset(&gm,0,sizeof(gm));
  35.         DWORD res = GetGlyphOutline(hDC,ch,GGO_NATIVE,&gm,dwSize,pBuff,&mat);
  36.         if (res!=dwSize)
  37.         {
  38.             free(pBuff);
  39.             pBuff = NULL;
  40.         }
  41.     }
  42.     if (pBuff)
  43.     {
  44.         BYTE * ptr = (BYTE *)pBuff;
  45.         while (dwSize>0)
  46.         {
  47.             TTPOLYGONHEADER * header = (TTPOLYGONHEADER *)ptr;
  48.             cnt ++;
  49.             ptr += header->cb;
  50.             dwSize -= header->cb;
  51.         }
  52.         free(pBuff);
  53.     }
  54.     SelectObject(hDC,hOldFont);
  55.     ReleaseDC(NULL,hDC);
  56.     return cnt;
  57. }

测试:
  1. union {
  2.     UINT ch;
  3.     char szText[4];
  4. } a;
  5. char * szText = "疆";
  6. a.ch = 0;
  7. a.szText[1] = szText[0];
  8. a.szText[0] = szText[1];
  9. int cnt = GetCharStrokes(a.ch);
  10. TRACE("/"%s/"的笔画%d/n",szText,cnt);
运行结果:
"疆"的笔画19