How can i get center x,y of my view in android?
Asked Answered
P

5

42

I am attaching an imageview up on my frame layout. Here i want to get my imageview center co-ordinates. i will use that same co-ordinates to set my imageview in next layout. Please suggest me how to get the center co-ordinates of my imageview.

Thanks in advance

Poulard answered 7/12, 2012 at 7:21 Comment(1)
After the view has been created? What have you tried?Gettysburg
R
85

centre of the imageView will be

 centreX=imageView.getX() + imageView.getWidth()  / 2;
 centreY=imageView.getY() + imageView.getHeight() / 2;

but make sure you call it after the imageView created

Rhomboid answered 7/12, 2012 at 7:42 Comment(4)
Seems getX() and getY() can not be used when api level below 11Badalona
What if the imageView is scaled ?Wordbook
this solution is only relative to parent view. If you want it to be global you should use the getLocationOnScreen or getLocationInWindow methodsCharismatic
centreX and centreY will be floatLakh
S
9

You can use getPivotX() and getPivotY(), it always keep in center of view even rotate view.

Subscribe answered 20/6, 2016 at 6:19 Comment(2)
Add some explanation with answer for how this answer help OP in fixing current issueBagpipe
@Subscribe : is it possible to get the center?Unquestioning
L
5

Try this :

ImageView my_image = (ImageView) findViewById(R.id.my_imageView);  

Rect rectf = new Rect();
my_image.getLocalVisibleRect(rectf);

Log.d("WIDTH        :",String.valueOf(rectf.width()));
Log.d("HEIGHT       :",String.valueOf(rectf.height()));
Log.d("left         :",String.valueOf(rectf.left));
Log.d("right        :",String.valueOf(rectf.right));
Log.d("top          :",String.valueOf(rectf.top));
Log.d("bottom       :",String.valueOf(rectf.bottom));

Hope this helps you.

Thanks.

Leanoraleant answered 7/12, 2012 at 7:56 Comment(0)
D
4

As @aiueoH mentioned, you can use getPivotX() and getPivotY().

Try using this for finding coordinates of centre:

int centreX = view.getPivotX()/2;
int centreY = view.getPivotY()/2;
Danella answered 26/6, 2017 at 13:8 Comment(1)
Perhaps divide by 2 is unneeded? The documentation states "If no pivot has been set then the pivot will be the center of the view."Thorne
L
2

if you wish to align a view at the center of other view then you can use this -

float center_x = parent_view.getX() + parent_view.getWidth()/2 - child_view.getWidth()/2;

and then obviously using -

child_view.setX(center_x);
Loiretcher answered 8/1, 2018 at 18:12 Comment(2)
This is perfect answer. when you want to set textview center in view than this solution works. above solutions not gives perfect center x.Woollyheaded
Working, thanksMaraud

© 2022 - 2024 — McMap. All rights reserved.