简体   繁体   中英

Java: Rectangles Width and Height

When I draw a rectangle like the following

drawRect(0,0,39,39);

Is the width and height in pixels both 40? When I draw the rectangle over an image that i know is 40x40 pixels and put this rectangle right over it, it fits perfectly. So I am a bit confused because the java website says the the 3rd and 4th variable refer to width and height, but if this is the case it doesn't really refer to the real width, just the actual width-1. I feel like I am missing something or maybe making a mistake. S

It will be 40x40.

http://developer.android.com/reference/android/graphics/Rect.html#Rect(int , int, int, int)

public Rect (int left, int top, int right, int bottom)

Added in API level 1
Create a new rectangle with the specified coordinates. Note: no range checking is performed, so the caller must ensure that left <= right and top <= bottom.

Parameters
left    The X coordinate of the left side of the rectangle
top The Y coordinate of the top of the rectangle
right   The X coordinate of the right side of the rectangle
bottom  The Y coordinate of the bottom of the rectangle

The last 2 parameters indicate right and bottom, so therefore if you start at 0 and go to 39 that's 40 pixels.

Your question is confusing two classes.

  • The Java java.awt.Rectangle class has a constructor with parameters as you describe: Rectangle(int x, int y, int width, int height) .

  • The Android android.graphics.Rect class has a constructor that takes different parameters: Rect (int left, int top, int right, int bottom) .

The Rect is NOT documented on the Java website, because it it NOT part of Java. If you've found documentation on the Java site, it is for the Rectangle class ... which is different.


If you incorrectly supply the Rect arguments as x,y,width,height you are likely to get burned. The javadoc for the Rect constructor says:

"Note: no range checking is performed, so the caller must ensure that left <= right and top <= bottom."

If you don't then expect strange things to happen.

(Note that Rect(0,0,39,39) violates the documented constraint ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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