Search code examples
.netgraphicsgdi+drawstring

Fill text inside rectangle


I'm using GDI+ to draw a string on a Graphics object.

I want the string to fit inside a pre-defined rectangle (without breaking any lines)

Is there's anyway of doing this besides using TextRenderer.MeasureString() in a loop until the desirable size is returned?

something like:

DrawScaledString(Graphics g, string myString, Rectangle rect)

Solution

  • You can use the ScaleTransform

    string testString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Suspendisse et nisl adipiscing nisl adipiscing ultricies in ac lacus.
    Vivamus malesuada eros at est egestas varius tincidunt libero porttitor.
    Pellentesque sollicitudin egestas augue, ac commodo felis ultricies sit amet.";
    
    Bitmap bmp = new Bitmap(300, 300);
    using (var graphics = Graphics.FromImage(bmp))
    {
        graphics.FillRectangle(Brushes.White, graphics.ClipBounds);
        var stringSize = graphics.MeasureString(testString, this.Font);
        var scale = bmp.Width / stringSize.Width;
        if (scale < 1)
        {
            graphics.ScaleTransform(scale, scale);
        }
        graphics.DrawString(testString, this.Font, Brushes.Black, new PointF());
    }
    bmp.Save("lorem.png", System.Drawing.Imaging.ImageFormat.Png);
    

    But you might get some alias effects.

    alt text

    Edit:

    But if you want to change the font size instead I guess you can change the font size with scale in the code above instead of using the scale transform. Try both and compare the quality of the result.