2012-03-27 12 views
6

favor ver mi código:medición cadena con Graphics.MeasureString

Graphics grfx = Graphics.FromImage(new Bitmap(1, 1)); 

System.Drawing.Font f = new System.Drawing.Font("Times New Roman", 10, FontStyle.Regular); 

const string text1 = "check_space"; 
SizeF bounds1 = grfx.MeasureString(text1, f); 

const string text2 = "check_space "; 
SizeF bounds2 = grfx.MeasureString(text2, f); 

Assert.IsTrue(bounds1.Width < bounds2.Width); // I have Fail here! 

Me pregunto por qué ha fallado mi prueba. ¿Por qué el texto con espacio en la cola es NO mayor por el ancho que el texto sin espacio?

ACTUALIZACIÓN: Entiendo que estas dos cadenas no son iguales. Pero a medida que comprendo mentalmente la cadena con, el espacio debe ser mayor por el ancho que la cadena sin espacio. No?

+0

¿Son iguales por casualidad? – Oded

+0

Pruebe con '" check_space. "' Y '" check_space. "'. Ellos no son iguales. –

+0

@Oded, @ L.B ver mi actualización –

Respuesta

12

tiene que indicarle que mida espacios al final, lo que no ocurre de forma predeterminada.

Graphics grfx = Graphics.FromImage(new Bitmap(1, 1)); 

System.Drawing.Font f = new System.Drawing.Font("Times New Roman", 10, FontStyle.Regular); 

string text1 = "check_space"; 
SizeF bounds1 = grfx.MeasureString(text1, f, new PointF(0,0), new StringFormat(StringFormatFlags.MeasureTrailingSpaces)); 

string text2 = "check_space "; 
SizeF bounds2 = grfx.MeasureString(text2, f, new PointF(0,0), new StringFormat(StringFormatFlags.MeasureTrailingSpaces)); 
+1

¡Guau! Thaks! Nunca he escuchado sobre esto –

Cuestiones relacionadas