简体   繁体   English

如何增加矩形的大小

[英]How to increase size of a rectangle

I want to increase the size of my rectangle by 10 pixels. 我想将矩形的大小增加10像素。 The following code seems not working. 以下代码似乎无效。 Assume sampleRect is my rectangle. 假设sampleRect是我的矩形。 Please let me know. 请告诉我。

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

It will work, but you can write the same thing more elegantly using the Inflate method : 它会起作用,但你可以使用Inflate方法更优雅地编写相同的东西:

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. 您的方法和Inflate方法之间的一个重要区别是您创建了一个新的矩形实例,而Inflate修改了一个现有的矩形。

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: 根据您对“以10像素增长”的定义,我会这样做:

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. 您拥有的代码将在x,y -10处与sampleRect相比创建一个新的Rectangle。 To compensate you increase the Width and Height with 20. 为了补偿你,用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. Rectangle.Inflate也会改变中心周围的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM