GDI+常见问题汇总

来源:互联网 发布:数据可视化工具有哪些 编辑:程序博客网 时间:2024/06/04 23:24

一、利用UpdateLayeredWindow,在GDI+绘制字体时,FontStyleRegular样式的字体会变成透明,而其它的样式都可以正常显示;

问题的原因是:
层窗口(WS_EX_LAYERED),用UpdateLayeredWindow输出的文字(用常规方法输出的:TextOut、DrawText、DrawString...),并且设置了AC_SRC_ALPHA和ULW_ALPHA,就会存在这种错误。
解决办法:

[cpp] view plaincopy
  1. void CGDIPlus_TextTestDlg::Redraw()  
  2. {  
  3.   CRect rect;  
  4.   GetClientRect(&rect);  
  5.   SolidBrush brush(Color(200,255,0,0));  
  6.   m_pGraphics->FillRectangle(&brush,0,0,rect.Width(),rect.Height());  
  7.   
  8.   CFont *pFont=GetFont();  
  9.   LOGFONT lf;  
  10.   pFont->GetLogFont(&lf);  
  11.   CComBSTR wszFN(lf.lfFaceName);  
  12.   int nHeight=-lf.lfHeight;  
  13.   FontFamily ff(wszFN,NULL);  
  14.   int nStyle=FontStyleRegular;  
  15.   Font font(&ff,nHeight,nStyle,UnitPixel);  
  16.   StringFormat format;  
  17.   format.SetAlignment(StringAlignmentNear);  
  18.   SolidBrush brush2(Color(255,0,0,0));  
  19.   int nStyle2=FontStyleBold;  
  20.   Font font2(&ff,nHeight,nStyle2,UnitPixel);  
  21.   
  22.   
  23.   //-----直接写字,变得穿透了  
  24.   CComBSTR wsz("文字Test: 直接写字,变得穿透了");  
  25.   m_pGraphics->DrawString(wsz,wsz.Length(),&font,PointF(50,50),&format,&brush2);  
  26.   
  27.   //-----文字加粗  
  28.   wsz="文字Test: 文字加粗";  
  29.   m_pGraphics->DrawString(wsz,wsz.Length(),&font2,PointF(50,70),&format,&brush2);  
  30.   
  31.   //-----SetTextRenderingHint(TextRenderingHintAntiAlias)  
  32.   wsz="文字Test: SetTextRenderingHint(TextRenderingHintAntiAlias)";  
  33.   GraphicsContainer gc=m_pGraphics->BeginContainer();  
  34.   m_pGraphics->SetTextRenderingHint(TextRenderingHintAntiAlias);  
  35.   m_pGraphics->DrawString(wsz,wsz.Length(),&font,PointF(50,90),&format,&brush2);  
  36.   m_pGraphics->EndContainer(gc);  
  37.   
  38.   //-----GraphicsPath  
  39.   wsz="文字Test: GraphicsPath";  
  40.   gc=m_pGraphics->BeginContainer();  
  41.   m_pGraphics->SetSmoothingMode(SmoothingModeHighQuality);  
  42.   GraphicsPath path(FillModeAlternate);  
  43.   path.AddString(wsz,wsz.Length(),&ff,nStyle,nHeight,PointF(50,110),&format);  
  44.   m_pGraphics->FillPath(&brush2,&path);  
  45.   m_pGraphics->EndContainer(gc);  
  46.   
  47.   SIZE sizeWindow = rect.Size();  
  48.   POINT ptSrc = { 0, 0 };  
  49.   BLENDFUNCTION blend;  
  50.   blend.BlendOp = AC_SRC_OVER;  
  51.   blend.BlendFlags = 0;  
  52.   blend.AlphaFormat = AC_SRC_ALPHA;  
  53.   blend.SourceConstantAlpha = 255;  
  54.   UpdateLayeredWindow(m_hWnd, hdcHWND, NULL, &sizeWindow, hdcHBMP, &ptSrc, 0, &blend, ULW_ALPHA);  
  55. }  
有三个方法避免,但是都不是真正的解决这个问题
第一个方法是字体加宽,把字体的Weight改成800就不会透
第二个方法是SetTextRenderingHint(TextRenderingHintAntiAlias)
第三个方法是把字串转换成GraphicsPath,然后用FillPath画出来,画之前SetSmoothingMode(SmoothingModeHighQuality)字会好看一点
不过,这三种方法都改变了字画出来的样子,第一种方法字被加粗了,第二三种方法字被抗锯齿了。 找到一个简单的方法同时避免穿透和变形的问题,把Color的Alhpa值改成254就好了。 使用DrawString + A->254 没问题。





原创粉丝点击