518抽奖软件源码之:GDI+上下左右中对齐
518抽奖软件源码之:GDI+上下左右中对齐在开发“518抽奖软件”的时候,需要用到GDI+的写文字功能。 GDI+在对齐方面比原来的GDI复杂些,主要是 StringFormat 的参数设置和行高的测定问题,详情参考下面的源码。
GDIPLUS(gdi+)对齐处理的函数源码
程序代码:
//单行文本,rc内对齐,align是水平对齐,valign是垂直对齐 // void Tapp::paint_str(HDC hDc, const WCHAR* str, LOGFONT& lf, COLORREF color, RECT& rc, WORD align, WORD valign) { if (!str) return; if (rc.right - rc.left <= 1 || rc.bottom - rc.top <= 1) return; StringFormat fmt; fmt.SetFormatFlags(StringFormatFlagsNoWrap | StringFormatFlagsNoClip | StringFormatFlagsMeasureTrailingSpaces); if (align == ALIGN_NEAR) fmt.SetAlignment(StringAlignmentNear); else if (align == ALIGN_CENTER) fmt.SetAlignment(StringAlignmentCenter); else fmt.SetAlignment(StringAlignmentFar); fmt.SetLineAlignment(StringAlignmentNear); RectF rcF; rcF.X = rc.left; rcF.Y = rc.top; rcF.Width = rc.right - rc.left; rcF.Height = rc.bottom - rc.top; FontFamily ff(lf.lfFaceName); Font gfont(hDc, &lf); SolidBrush bru(Color(GetRValue(color), GetGValue(color), GetBValue(color))); Graphics g(hDc); int style = FontStyleRegular; if (lf.lfItalic) style = FontStyleItalic; if (lf.lfWeight == FW_BOLD) style = FontStyleBold; if (lf.lfItalic && lf.lfWeight == FW_BOLD) style = FontStyleBoldItalic; double r = (double)(ff.GetCellAscent(style) + ff.GetCellDescent(style)) / (double)ff.GetLineSpacing(style); if (align == ALIGN_NEAR) rcF.Width += 500.0; else if (align == ALIGN_FAR) { rcF.X -= 500.0; rcF.Width += 500.0; } else { rcF.X -= 500.0; rcF.Width += 1000.0; } if (valign == ALIGN_NEAR) rcF.Height += 500.0; else if (valign == ALIGN_CENTER) { rcF.Y -= 500.0; rcF.Height += 1000.0; rcF.Y += ((rcF.Height - gfont.GetHeight(&g)*r) / 2.0); } else { rcF.Y -= 500.0; rcF.Height += 500.0; rcF.Y += (rcF.Height - gfont.GetHeight(&g)*r); } SetTextRenderingHint(TextRenderingHintAntiAlias); g.DrawString(str, -1, &gfont, rcF, &fmt, &bru); }