2014-06-14 60 views
2

有代碼:拉繩大膽和普通文本

using (Graphics g = Graphics.FromImage(pictureBox1.Image)) 
      { 

       Font drawFont = new Font("Arial", 12); 
       Font drawFontBold = new Font("Arial", 12, FontStyle.Bold); 
       SolidBrush drawBrush = new SolidBrush(Color.Black); 
       g.DrawString("this is normal", drawFont, drawBrush, new RectangleF(350f, 250f, 647, 200)); 
       g.DrawString(" and this is bold text", drawFontBold, drawBrush, new RectangleF(350f, 250f, 647, 200)); 
      } 

我需要得到

這是正常的,這是大膽的文字

但我收到第二覆蓋第一個文字

+2

矩形指定positiom。兩個文本具有相同的座標。 – alko989

+0

在第二個DrawString中更改647和200,關於正確調用MeasureString方法來連接它 – Nigrimmist

回答

2

試試這個代碼,可能會做th電子工作。

using (Graphics g = Graphics.FromImage(pictureBox1.Image)) 
{ 
    Font drawFont = new Font("Arial", 12); 
    Font drawFontBold = new Font("Arial", 12, FontStyle.Bold); 
    SolidBrush drawBrush = new SolidBrush(Color.Black); 

    // find the width of single char using selected fonts 
    float CharWidth = g.MeasureString("Y", drawFont).Width; 

    // draw first part of string 
    g.DrawString("this is normal", drawFont, drawBrush, new RectangleF(350f, 250f, 647, 200)); 

    // now get the total width of words drawn using above settings 
    float widthFirst = ("this is normal").Length() * CharWidth; 

    // the width of first part string to start of second part to avoid overlay 
    g.DrawString(" and this is bold text", drawFontBold, drawBrush, new RectangleF(350f + widthFirst, 250f, 647, 200)); 
} 
+4

這更有助於解釋您的答案,而不是僅僅發佈代碼。 –

+2

增加了評論,上次有點匆忙。謝謝你的觀點。 –

+0

'float widthFirst =(「this is normal」)。Length()* CharWidth' - 你在開玩笑嗎?! 「Arial」不是一種等寬字體 - 即使是等寬字體也不會以這種方式實現(有一些變音符號,例如Hangul«+»+«+»»»= «하ᇶ»等)!只要做'float widthFirst = g.MeasureString(「this is normal」,drawFont).Width'。 – Sasha

1

我會建議使用:

float widthFirst = g.MeasureString("this is normal", drawFont).Width;