一、利用UpdateLayeredWindow,在GDI+绘制字体时,FontStyleRegular样式的字体会变成透明,而其它的样式都可以正常显示;
问题的原因是:
层窗口(WS_EX_LAYERED),用UpdateLayeredWindow输出的文字(用常规方法输出的:TextOut、DrawText、DrawString...),并且设置了AC_SRC_ALPHA和ULW_ALPHA,就会存在这种错误。
解决办法:
- void CGDIPlus_TextTestDlg::Redraw()
- {
- CRect rect;
- GetClientRect(&rect);
- SolidBrush brush(Color(200,255,0,0));
- m_pGraphics->FillRectangle(&brush,0,0,rect.Width(),rect.Height());
- CFont *pFont=GetFont();
- LOGFONT lf;
- pFont->GetLogFont(&lf);
- CComBSTR wszFN(lf.lfFaceName);
- int nHeight=-lf.lfHeight;
- FontFamily ff(wszFN,NULL);
- int nStyle=FontStyleRegular;
- Font font(&ff,nHeight,nStyle,UnitPixel);
- StringFormat format;
- format.SetAlignment(StringAlignmentNear);
- SolidBrush brush2(Color(255,0,0,0));
- int nStyle2=FontStyleBold;
- Font font2(&ff,nHeight,nStyle2,UnitPixel);
- //-----直接写字,变得穿透了
- CComBSTR wsz("文字Test: 直接写字,变得穿透了");
- m_pGraphics->DrawString(wsz,wsz.Length(),&font,PointF(50,50),&format,&brush2);
- //-----文字加粗
- wsz="文字Test: 文字加粗";
- m_pGraphics->DrawString(wsz,wsz.Length(),&font2,PointF(50,70),&format,&brush2);
- //-----SetTextRenderingHint(TextRenderingHintAntiAlias)
- wsz="文字Test: SetTextRenderingHint(TextRenderingHintAntiAlias)";
- GraphicsContainer gc=m_pGraphics->BeginContainer();
- m_pGraphics->SetTextRenderingHint(TextRenderingHintAntiAlias);
- m_pGraphics->DrawString(wsz,wsz.Length(),&font,PointF(50,90),&format,&brush2);
- m_pGraphics->EndContainer(gc);
- //-----GraphicsPath
- wsz="文字Test: GraphicsPath";
- gc=m_pGraphics->BeginContainer();
- m_pGraphics->SetSmoothingMode(SmoothingModeHighQuality);
- GraphicsPath path(FillModeAlternate);
- path.AddString(wsz,wsz.Length(),&ff,nStyle,nHeight,PointF(50,110),&format);
- m_pGraphics->FillPath(&brush2,&path);
- m_pGraphics->EndContainer(gc);
- SIZE sizeWindow = rect.Size();
- POINT ptSrc = { 0, 0 };
- BLENDFUNCTION blend;
- blend.BlendOp = AC_SRC_OVER;
- blend.BlendFlags = 0;
- blend.AlphaFormat = AC_SRC_ALPHA;
- blend.SourceConstantAlpha = 255;
- UpdateLayeredWindow(m_hWnd, hdcHWND, NULL, &sizeWindow, hdcHBMP, &ptSrc, 0, &blend, ULW_ALPHA);
- }
第一个方法是字体加宽,把字体的Weight改成800就不会透
第二个方法是SetTextRenderingHint(TextRenderingHintAntiAlias)
第三个方法是把字串转换成GraphicsPath,然后用FillPath画出来,画之前SetSmoothingMode(SmoothingModeHighQuality)字会好看一点
不过,这三种方法都改变了字画出来的样子,第一种方法字被加粗了,第二三种方法字被抗锯齿了。