2009-06-09 13 views
10

¿Cuál es la mejor manera de dibujar la cadena en el centro de un rectánguloF? El tamaño de la fuente de texto puede reducirse para adaptarse. En la mayoría de los casos, el texto es demasiado grande para caber con una fuente determinada, por lo que debe reducir la fuente.Dibujar texto en el centro

Respuesta

3

Se está trabajando para mí sé. Esto es lo que hice

Size textSize = TextRenderer.MeasureText(Text, Font); 
float presentFontSize = Font.Size; 
Font newFont = new Font(Font.FontFamily, presentFontSize, Font.Style); 
while ((textSize.Width>textBoundary.Width || textSize.Height > textBoundary.Height) && presentFontSize-0.2F>0) 
{ 
    presentFontSize -= 0.2F; 
    newFont = new Font(Font.FontFamily,presentFontSize,Font.Style); 
    textSize = TextRenderer.MeasureText(ButtonText, newFont); 
} 
stringFormat sf; 
sf.Alignment = StringAlignment.Center; 
sf.LineAlignment = StringAlignment.Center; 
e.Graphics.DrawString(Text,newFont,Brushes.Black,textBoundary, sf); 
+0

Vi que había publicado su solución de trabajo cuando publiqué mi versión, pero dejo la mía porque es más eficiente (obtiene el tamaño de fuente sin bucles) y también creo que su código puede perder memoria, creando muchos objetos de fuentes pero no llamando Dispose en ellos. –

+1

¿Cuál es el valor del parámetro 'textBoundary'? Por favor, declarar e inicializarlo. –

+0

OK, LO CONSEGUÍ. textBoundary se crea como se ve a continuación String imgsrc = "RUTA DE ARCHIVO DE IMAGEN EN DISCO"; Bitmap bmp = new Mapa de bits (System.Drawing.Image.FromFile (imgsrc)); RectangleF textBoundary = new Rectangle (0, 0, bmp.Width, bmp.Height - 30); –

0

Determine el tamaño del texto que se dibujará y luego determine el desplazamiento para el inicio de la cadena desde el centro del rectánguloF y sáquelo.

0

Obtenga width/2 y height/2 del rectángulo, luego use System.Graphics.MeasureString para obtener las dimensiones de su cadena, de nuevo la mitad y reste de sus valores anteriores de ancho/alto y termine con la X , Coordenada Y para dibujar la cuerda a fin de que esté centrada.

16

Este código centra el texto en horizontal y en vertical:

stringFormat sf; 
sf.Alignment = StringAlignment.Center; 
sf.LineAlignment = StringAlignment.Center; 
grp.DrawString(text, font, Brushes.Black, rectf, sf); 
+0

¿qué tal reducir el tamaño de la fuente? – Prithis

10

He jugado un poco con él un poco y encontré esta solución (suponiendo que el RectangleF rect y string text ya están definidos):

StringFormat stringFormat = new StringFormat() 
{ 
    Alignment = StringAlignment.Center, 
    LineAlignment = StringAlignment.Center 
}; 

using (Graphics g = this.CreateGraphics()) 
{ 
    SizeF s = g.MeasureString(text, this.Font); 
    float fontScale = Math.Max(s.Width/rect.Width, s.Height/rect.Height); 
    using (Font font = new Font(this.Font.FontFamily, this.Font.SizeInPoints/fontScale, GraphicsUnit.Point)) 
    { 
     g.DrawString(text, font, Brushes.Black, rect, stringFormat); 
    } 
} 
0

Fácil de usar :)

public static void DrawStringCenter(Image image, string s, Font font, Color color, RectangleF layoutRectangle) 
    { 
     var graphics = Graphics.FromImage(image); 

     var brush = new SolidBrush(color); 

     var format = new StringFormat 
     { 
      Alignment = StringAlignment.Center, 
      LineAlignment = StringAlignment.Center 
     }; 

     graphics.DrawString(s, font, brush, layoutRectangle, format); 
    } 
Cuestiones relacionadas