public static void SizeTextRectangleToText(this ToolStripItemTextRenderEventArgs args)
{
var textSize = args.Graphics.MeasureString(args.Text, args.TextFont);
const int padding = 2;
var rc = args.TextRectangle;
var changed = false;
// adjust the rectangle to fit the calculated text size
if (rc.Width < textSize.Width + padding)
{
var diffX = (int)System.Math.Ceiling(textSize.Width + 2 - rc.Width);
rc.X -= diffX / 2;
rc.Width += diffX;
changed = true;
}
if (rc.Height < textSize.Height + padding)
{
var diffY = (int)System.Math.Ceiling(textSize.Height + 2 - rc.Height);
rc.Y -= diffY / 2;
rc.Height += diffY;
changed = true;
}
// if nothing changed, return now
if (!changed) return;
args.TextRectangle = rc;
}