2
votes

Does GDI have any method of setting an overall clipping area, in the same way the GDI+ Graphics object does?

Specifically:

  • Graphics.DrawString uses GDI+ which includes the clipping bounds system.
  • TextRenderer.DrawText uses GDI which does not.

My new scrollbar system automatically resizes the Graphics draw area as needed. While tidying up a control which uses it, I switched some inline string rendering calls over to my text layout class, which uses TextRenderer.DrawText. I can't quite remember why I used that instead of just Graphics.DrawString, but before I refactor that I wanted to check if there was some way of fixing the problem as it stands.

public class GraphicsClipExample : Form
{
    public GraphicsClipExample()
    {
        this.ClientSize = new Size(this.ClientSize.Width, 100);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // update the graphics clip area
        e.Graphics.Clear(Color.Cyan);
        e.Graphics.SetClip(new Rectangle(0, 0, e.ClipRectangle.Width, 50));
        e.Graphics.Clear(Color.Magenta);

        Font font = new Font("Calibri", 24);
        e.Graphics.DrawString("Testing", font, Brushes.Black, 10, 28);

        TextRenderer.DrawText(e.Graphics, "Testing", font, new Point(150, 28), Color.Black);
    }
}

This produces the following output:

GDI vs GDI+ : Clipping

Is there any way to provide a simple clipping area for GDI overall, or TextRenderer specifically?

Many thanks

1

1 Answers

4
votes

Try using the PreserveGraphicsClipping format flag:

  TextRenderer.DrawText(e.Graphics, "Testing", font, new Point(150, 28),
                        Color.Black, Color.Empty,
                        TextFormatFlags.PreserveGraphicsClipping);