Rex Hui
Rex Hui

Reputation: 71

c# System.Windows.Rect struct Width and Height

If I do this:

Rect rc = new Rect(0, 0, 10, 5);

I am creating a rectangle at position 0, 0 with a width of 10 and height of 5. So rc.Width is 10 and rc.Heightis 5.

But how come rc.Right is 9 instead of 10 and rc.Bottom is 5 instead of 4?

Upvotes: 3

Views: 2860

Answers (3)

Victor Zakharov
Victor Zakharov

Reputation: 26434

EDIT: Actually, Rect also works as you expect, I tried in Visual Studio 2017:

enter image description here

Are you using some other Rect? Below is decompiled code for calculating Bottom:

/// <summary>
/// Bottom Property - This is a read-only alias for Y + Height
/// If this is the empty rectangle, the value will be negative infinity.
/// </summary>
public double Bottom
{
    get
    {
        if (IsEmpty)
        {
            return Double.NegativeInfinity;
        }

        return _y + _height; //notice it's just top + height, no magic
    }
}

Old answer - Use Rectangle. It works as you expect:

Rectangle rc = new Rectangle(0, 0, 10, 5);

enter image description here

Upvotes: 2

Soviut
Soviut

Reputation: 91585

This is because the coordinate system is zero-based starts at (0, 0).

So a rectangle with a width of 10 has its starting point at 0 and if you count out 10 units, the right-most coordinate will be 9.

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Upvotes: 0

Chris Zimmerman
Chris Zimmerman

Reputation: 331

Because locations are zero based. The 3rd parameter defines the width in pixels, in this case, 10 pixels. So, it starts at zero, and is 10 pixels long, which means the rightmost location is at 9. The same principle applies to height as well, which explains the bottom.

Upvotes: 2

Related Questions