Voici une autre solution au problème, il est un peu intensive car elle nécessite un peu juste de la création et la destruction police, mais peut mieux fonctionner, en fonction de votre situation et les besoins:
public class RenderInBox
{
Rectangle box;
Form root;
Font font;
string text;
StringFormat format;
public RenderInBox(Rectangle box, Form root, string text, string fontFamily, int startFontSize = 150)
{
this.root = root;
this.box = box;
this.text = text;
Graphics graphics = root.CreateGraphics();
bool fits = false;
int size = startFontSize;
do
{
if (font != null)
font.Dispose();
font = new Font(fontFamily, size, FontStyle.Regular, GraphicsUnit.Pixel);
SizeF stringSize = graphics.MeasureString(text, font, box.Width, format);
fits = (stringSize.Height < box.Height);
size -= 2;
} while (!fits);
graphics.Dispose();
format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
}
public void Render(Graphics graphics, Brush brush)
{
graphics.DrawString(text, font, brush, box, format);
}
}
Pour l'utiliser simplement créer une nouvelle classe et appeler Render(). Notez que ceci est spécifiquement écrit pour le rendu à un formulaire.
var titleBox = new RenderInBox(new Rectangle(10, 10, 400, 100), thisForm, "This is my text it may be quite long", "Tahoma", 200);
titleBox.Render(myGraphics, Brushes.White);
Vous devez créer l'objet RenderInBox dès le départ en raison de sa nature de création intensive. Par conséquent, il ne convient pas à tous les besoins.
Vous pouvez appliquer une transformation matricielle, mais cela fait des années que je n'y ai pas touché. – leppie
N'est-ce pas un peu de frais généraux? – Nissim