1

I am learning about GraphicsPath and Region. And using it with Invalidate.

So, I have a Rectangle object and I want to erase this rectangle. But, I only want to erase the edge of the rectangle (that is, the lines).

At the moment I have this:

if(bErase)
{
    Rectangle rcRubberBand = GetSelectionRectangle();

    GraphicsPath path = new GraphicsPath();
    path.AddRectangle(rcLastRubberBand);
    Region reg = new Region(path);
    myControl3.Invalidate(reg);
    myControl3.Update();
}

It works, but it is invalidating the complete rectangle shape. I only need to invalidate the rectangle lines that I had drawn. Can I make such a path with GraphicsPath?

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164

1 Answers1

2

You can't get the system to invalidate anything but a full rectangle.

So you can't use an outline path to save time.

However it can be useful for other things. Let's look at two options :

  • You can create an outline path
  • You can exclude parts of a region

The simplest way to create an outline GraphicsPath is to widen a given path with a Pen:

GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(r0);
using (Pen pen = new Pen(Color.Green, 3f)) gp.Widen(pen); 

This let's you make use of all the many options of a Pen, including DashStyles, Alignment, LineJoins etc..

An alternative way is to create it with the default FillMode.Alternate and simply add a smaller figure:

Rectangle r0 = new Rectangle(11, 11, 333, 333);
Rectangle r1 = r0;
r1.Inflate(-6, -6);
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(r0);
gp.AddRectangle(r1);

Now you can fill the path

g.FillPath(Brushes.Red, gp);

or use it to clip the ClipBounds of a Graphics object g :

g.SetClip(gp);

After this anything you draw including a Clear will only affect the pixels inside the outline.

When you are done you can write:

g.ResetClip();

and continue drawing on the full size of your graphics target.

Or you can use the path as the basis for a Region:

Region r = new Region(gp);

and restrict a Control to it..:

somecontrol.Region = r;

Regions support several set operations so instead of using the above outline path you could also write this with the same result:

Region r = new Region(r0);
r.Exclude(r1);
TaW
  • 53,122
  • 8
  • 69
  • 111