Visual C# 2005 - 如何利用程式碼產生多變化字體之倒影字

摘要:Visual C# 2005 - 如何利用程式碼產生多變化字體之倒影字

除了圖像之外,如果要針對文字做出繪圖變化,則利用 .Net FrameworkSystem.Drawing 命名空間中的 Graphics Brush 類別最是簡便。接下來我們將介紹如何運用筆刷來產生帶有倒影效果的文字。 

程式範例 

圖表1 

圖表 1 所示的程式範例示範如何利用 Graphics 類別的 DrawString 方法,產生帶有倒影效果的文字,程式碼如下所示: 

SizeF textSize;
Graphics g;
Brush myBackBrush = Brushes.Gray;
Brush myForeBrush = Brushes.Blue;
Font myFont = new Font("Times New Roman",
  (float)this.nudFontSize.Value, FontStyle.Regular);
GraphicsState myState;
float xLocation, yLocation;
float textHeight;

g = picDemoArea.CreateGraphics();
g.Clear(Color.White);

textSize = g.MeasureString(this.txtShortText.Text, myFont);

xLocation = (picDemoArea.Width - textSize.Width) / 2;
yLocation = (picDemoArea.Height - textSize.Height) / 2;

g.TranslateTransform(xLocation, yLocation);

int lineAscent;
int lineSpacing;
float lineHeight;

lineAscent = myFont.FontFamily.GetCellAscent(myFont.Style);
lineSpacing = myFont.FontFamily.GetLineSpacing(myFont.Style);
lineHeight = myFont.GetHeight(g);
textHeight = lineHeight * lineAscent / lineSpacing;

//
產生正倒影文字。
//int lineDescent;
//lineDescent =
//  myFont.FontFamily.GetCellDescent(myFont.Style);
//textHeight = lineHeight * (lineAscent + lineDescent) /
//  lineSpacing;

myState = g.Save();

g.ScaleTransform(1, -1.0f);
g.DrawString(txtShortText.Text, myFont, myBackBrush, 0,
  -textHeight);

g.Restore(myState);

g.DrawString(txtShortText.Text, myFont, myForeBrush, 0,
  -textHeight);