How to create a method to rotate a Rectangle object?

Ex:

Rectangle rect = new Rectangle(30, 30, 100, 400);

Center position: (65, 215).

Top = 30; Bottom = 430; Left = 30; Right = 130;

// 90 degrees
rect.Rotate(90);

Center position: (65, 215);

Top = 165; Bottom = 265; Left = -135; Right = 265;

The built-in Rectangle struct represents an axis-aligned rectangle. You can make an extension method to rotate it a quarter around it’s center if that’s what you need specifically. Just create a new Rectangle with the same center and flipped width and height.

and how would a calculation with 45 degrees?

That’s not possible because Rectangle represents an axis-aligned rectangle. You’ll need a custom type for an oriented rectangle.

1 Like