Clearing a rectangle in a Graphics


#1

I have a Graphics created on an Image, like this

Graphics g (image);

how do I clear a rectangle inside the Graphics, so that all the pixels in the area are replaced with Colours::transparentBlack, for example.

I have tried this:

g.setColour (Colours::transparentBlack);
g.fillRect (myArea);

but that does nothing (which has some kind of sense, as I am asking the Graphics to paint that rectangle with a dry brush, so to say, thus no pixels in that area change).

I have also tried this:

image.clear (myArea, Colours::transparentBlack);

which seemed more appropriate to actually replace the content of the area, but that’s not good either: turns out the implementation of that method does exactly the same steps above with fillRect.

I think that correcting the behaviour of Image::clear() now could break some existing code (despite it’s actually not-so-formally-correct), so what about adding a Graphics::clear() method that does what expected? Or maybe name it fillReplacing if you feel it’s more appropriate


#2

Graphics contexts can only paint over existing content, but Image::clear will certainly be able to clear a chunk of an image in the way you’re asking for.


#3

I must be missing something then.

I expect the following (test) code to draw a yellow border around the the component, then

  1. creates a 100x100 image
  2. fills it with transparent red
  3. clears only a portion of it, according to my calcs it should be the rectangle x=30, y=30, w=50, h=50
  4. paints the image in (10, 10)

This is what I get

As you can see, the red square has no “hole” inside it. What am I doing wrong?


#4

Hmm. Try “image.getBounds () / 2.0f” instead of 2

Looks like my new Rectangle operators don’t handle integer division very well - thanks, I’ll sort that out!


#5

Oh… yes, I see it now, it’s that nasty “/ 2” that makes it 1 / 2 = 0.

Hmm one more thought about this, though: if integers are valid arguments for the * and / operators, what about changing their template typename to a generic Type rather than FloatType?


#6

It’s ok, I’ve sorted it out now so it should handle integers too.


#7

Yeah, what I meant is: since the scale factor can also be an integer after these changes, what’s the point of calling its template type “FloatType”? It’s kinda misleading now since I now can divide a Rectangle by an integer constant and have its coordinates all divived as expected (according to integer division rules)


#8

True enough!