I am trying to draw a rectangle over a canvas and I am facing troubles to understand the in-depth of rectangle draw of Android. I've read tutorials and every possible but I am stuck.
Here in the image , the red rectangle is my target.
Irrespective of any rectangle size I need to draw the red rectangle bit above the base and in the middle of the rectangle. The worst nightmare I am facing here is understanding the X,Y Width and Height coordinates.
Can anyone explain how that math works, sometime we go up , Y reaches to very small but same width coordinates are higher. And I am never able to justify red inner rectangle properly.In some screen it works well in some other it fails. The red rectangle sometimes come out of the parent rectangle.
Agenda is to understand how coordinates work and ensure the integrity of inner red rectangle
It'll be great to get an explanation based on an example. I am using-
void drawRect(float left, float top, float right, float bottom, Paint paint)
to drawing the rectangle
X runs horizontally, from left to right. Y runs vertically, from top to bottom. It's exactly the same as on your graphics. So (0/0) is at top left.
When you go "up" Y will of course get smaller, as it grows from top to bottom.
You have to pay attention to laying out elements like ListViews, these will give a partial (or new, you cannot tell) canvas to your views that are drawn. These views will have 0x0 at their own top/left position. If you need the absolute you have to subsequently call View.getLocationOnScreen()
and calculate offsets yourself.
canvas.drawRect(left,top,right,bottom,paint);
In this
left: distance of the left side of rectangular from left side of
canvas.
top:Distance of top side of rectangular from the top side of
canvas
- right:distance of the right side of rectangular from left side of
canvas.
- bottom: Distance of the bottom side of rectangle from top side of canvas.
This will make sense.
float left = 100, top = 100; // basically (X1, Y1)
float right = left + 100; // width (distance from X1 to X2)
float bottom = top + 100; // height (distance from Y1 to Y2)
Thus
RectF myRectum = new RectF(left, top, right, bottom);
canvas.drawRect(myRectum, myPaint);