tags:

views:

64

answers:

4

I want to increase the size of my rectangle by 10 pixels. The following code seems not working. Assume sampleRect is my rectangle. Please let me know.

Rectangle temp = new Rectangle(
    sampleRect.X - 10, 
    sampleRect.Y - 10, 
    sampleRect.Width + 2*10, 
    sampleRect.Height + 2*10); 
+4  A: 

It will work, but you can write the same thing more elegantly using the Inflate method:

rect.Inflate(10, 10);

One important difference between your approach and Inflate method is that you create a new rectangle instance, while Inflate modifies an existing rectangle.

Tomas Petricek
Rectangle is a value type; changes to it will not affect others as they (necessarily) will be copies.
Ron Warholic
@Ron Doesn't matter if it's a value type; it's not immutable
Josh Stodola
@Josh: It isn't a case of immutability; its a case of reference versus value typing. `Inflate` mutates his existing `Rectangle` but no other code can hold a reference to it so they will always still hold the old value unless they re-read it. In Tomas's answer it was suggested that code holding references to the existing rectangle would automatically see the mutated value.
Ron Warholic
Good point about the value type - I deleted the last sentence (which would only make sense for reference types). Mutable value types are confusing!
Tomas Petricek
@Ron My bad... I see what you mean now
Josh Stodola
A: 

I'm not sure why you would ask "will this work" - try it!

However,

 someRectangle.Inflate(10,20);
 //or 
 someRectangle.Inflate(10);

should work

Philip Rieck
A: 

The code you have will make a new Rectangle at x,y -10 compared to the sampleRect. To compensate you increase the Width and Height with 20.

I assume you are trying to increase the rectangle around the center, in that case you need to move the rectangle half of the new increase.

Example:

var sizeIncrease = 10;
var newX = sampleRect.X - 0.5 * sizeIncrease;
var newY = sampleRect.Y - 0.5 * sizeIncrease;
var newWidth = sampleRect.Width + sizeIncrease;
var newHeight = sampleRect.Height + sizeIncrease;

These values should give you what you are looking for

Rectangle.Inflate will also change the size around the center.

Arkain
A: 

Depending on your definition of "grow by 10 pixels", here is what I would do:

int size = 10;
int halfSize = size/2;
Rectangle temp = new Rectangle(
    sampleRect.X - halfSize, 
    sampleRect.Y - halfSize, 
    sampleRect.Width + size, 
    sampleRect.Height + size); 
rein