Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scale a Rectangle

Status
Not open for further replies.

dragonwell

Programmer
Oct 21, 2002
863
US
How can I change the width and height of a System.Drawing.Rectangle object, by a small percentage? If my Rectangle is 100 wide by 50 high, say I want to scale it by 1.02 or .98776 percent? By multiplying the perncentage times the original size, I end up with a Single, and it seems the Rectangle's dimensions can only be Integers.
so
Code:
Single percentOfChange = .98776;

//since Width is an integer, this won't work
myRectangle.Width = myRectangle.Width * percentOfChange;

//...and this forces the percentage to 0
myRectangle.Width = (int)(myRectangle.Width * percentOfChange);

I'm sure this is just simple math.... but not simple enough for me. [sad]





[pipe]
 
Almost too embarassing...
Code:
float percentOfChange = .98776;
float newWidth = myRectangle.Width * percentOfChange
myRectangle.Width = (int)newWidth;

loses a little in the rounding but it's not too bad for pixels

[pipe]
 
I was thinking that you might want to take the smaller of the two dimensions (width or height) and run it through your algorithm. If rounded_output = input, then don't scale either dimension at all, as the percentage change is too small.

If you don't do this, then there is a small risk that the larger dimension may change while the smaller one remains the same, thus changing the aspect ratio of the window...
 
Thanks for the input. That makes sense. Everything's working fine, almost. After a few scalings the aspect ratio starts to drift out of proportion. FYI, I'm implementing a fixed-proportion cropping-box for images, that lets the user specify the output size, but adjust the size of the crop area (like in Photoshop). I haven't been able to find any examples of this. I think I should download the source for Gimp and look at it. I'll try your suggestion first, though.

[pipe]
 
Subclass Rectangle, adding some float values Fwidth and Fheight. These hold the 'real' size, and any arithmetic for resizing getsdone on them. The private rounded integer values are recalculated each time the floats change, and are just used to set the size in pixels. This should stop the aspect ratio drift as the errors won't accumulate.
 
You can even add a ScaledResize(float percentage) method, and encapsulate the whole lot...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top