Clipping Rectangles in FireMonkey

In experimenting with FireMonkey I came across what I thought was a non-obvious trick related to creating clipping rectangles in FireMonkey. In VCL we had the CreateRectRgn from the Windows API that allowed us to create areas when drawing commands would not venture beyond. Convenient for example if you have a plotting canvas and don’t want the marker symbols to spill out of the plot rectangle if they happen to be near the edges of the axes. In VCL it was straight forward to create a clipped area. In FireMonkey it isn’t so obvious. An examination of the documentation showed two promising methods, called ExcludeClipRect and IntersectClipRect. If one tries to use them however, nothing seems to happen. It was only though looking at the FireMonkey source code that I realized one must save the state of the canvas first using Canvas.SaveState, then call one of the clipping routines, do your drawing, then restore the canvas state. For example:

// Example of IntersectClipRect
Save := Canvas.SaveState;  
try   
  Canvas.IntersectClipRect (TRectF.Create(20, 20, 100, 100)); 
  Canvas.Fill.Color := claRed;
  Canvas.FillEllipse (TRectF.Create (50, 50, 150, 150), 100);
finally
  Canvas.RestoreState(Save); 
end;

// Example of ExcludeClipRect
Save := Canvas.SaveState; 
try   
  Canvas.ExcludeClipRect(TRectF.Create(60, 210, 90, 240));
  Canvas.Fill.Color := claBlue;
  Canvas.FillEllipse(TRectF.Create (50, 200, 100, 250), 100);
  p1.Create 60, 210, 90, 240);
  Canvas.DrawRect(p1, 0, 0, AllCorners, 100); 
finally   
  Canvas.RestoreState(Save);
 end;

Before Clipping (Gray rectangles drawn to highlight clipping area, not in code above):

After Clipping:

This entry was posted in Delphi, Programming, Software. Bookmark the permalink.

0 Responses to Clipping Rectangles in FireMonkey

  1. alan says:

    like clipping a picture in a circle?

  2. alan says:

    can you clip a rectangle in a circle?

Leave a Reply

Your email address will not be published.