开发者

How to increase size of a rectangle

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.Hei开发者_如何转开发ght + 2*10); 


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.


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

However,

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

should work


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); 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜